Huw Collingbourne

C# is one of the most widely used object-oriented programming (oop) languages. But what exactly is object orientation, and how can it be used in C# programs?

Let’s first consider what an ‘object’ actually is. In essence, an object is a structure that is able to contain both data and behavior. All the data items in a C# program – from a string such as “Hello world” to a treasure in a game – are wrapped up inside objects.

除了数据外,对象还可能包含功能,这些函数在面向对象的术语中称为“方法”。您可以使用这些方法来操纵对象的数据。例如,我可能会编写一个称为toupper()的函数,以返回大型情况中的字符串或称为timesten()的函数,以返回一个乘以10的整数值。

Person coding on laptop

Classes and Objects

You create each object from a ‘class.’ You can think of a class as a blueprint that defines both the data (the variables) and the object’s behavior (the methods). Let’s look at an example of a very simple class definition:

class MyClass { private string _s; public MyClass() { _s = "Hello world"; } public string GetS() { return _s; } public void SetS(string aString) { _s = aString; } }
Learn C# Programming (In Ten Easy Steps)

Last Updated August 2019

  • 126 lectures
  • Beginner Level
4.3 (1,061)

The simplest way to learn C# programming. |By Huw Collingbourne

探索课程

A class is defined using the class keyword. Here I have decided to call the class MyClass. It contains a string, _s. I’ve made this string ‘private,’ meaning code outside the class cannot access the string variable. To access the string, any code outside the class must use the methods I’ve written for that purpose – GetS() and SetS(). Sometimes an object is termed an ‘instance’ of a class.

封装和数据隐藏

The ability to put both data and functions into a class is called ‘encapsulation.’ In non-object-oriented languages, functions are ‘free-standing,’ meaning objects do not contain them.

At a simple level, encapsulation can be thought of as a way of structuring code more neatly. However, to realize the full power of encapsulation, you need to do ‘data-hiding.’ This is what I’ve done in the code above by making the _s variable private. That variable now hides from code outside MyClass. To set or get the value of _s, you must use the public data-access methods: GetS() and SetS().

严格封装的对象就像是一个密封的盒子。从框外,您看不到它的包含。您只知道它的行为。您发送消息。它返回答复 - 就像一台老式的大型计算机一样,将打孔卡进给了(消息),并从中产生了印刷输出的卷(答复)。这个过程使得撰写课程的程序员可以确定其他程序员有义务在该类中使用明确定义的路由,从而避免通过对数据进行意外或无效的更改引起的错误。带有数据隐藏的封装有时称为“黑匣子封装”。

访问数据智慧h Methods

By using methods to access variables, you are able to test that data is valid (before assigning or returning values) and control how much access is permitted to the variables inside an object. A method could, for example, restrict the amount of currency that can be returned from an internal variable called some_money, whereas if that variable were public and so could be accessed directly, the user would be able to withdraw any amount of currency with no limit.

At this point, the MyClass class doesn’t actually do anything. It is simply a definition or ‘blueprint’ for objects which don’t yet exist. In order to use the MyClass class, I need to create anobject从中。为此,我首先声明myllass类型的对象变量:

MyClass ob;

但是在我可以使用该对象之前,我需要创建它。我通过使用新关键字来做到这一点。这调用了myClass构造函数方法,并返回了我在此处分配给OB变量的新的myClass对象:

ob = new MyClass();

Constructors

Aconstructor是一种特殊的方法,在C#中具有与类本身相同的名称。这是MyClass构造函数:

民众MyClass() { _s = "Hello world"; }

这个构造函数中的代码分配字符串“Hello world” to the variable _s. You aren’t obliged to write any code in a constructor. However, it is quite common – and good practice – to assign default values to an object’s ‘fields’ or variables in the constructor. I have also written a SetS() method:

民众void SetS(string aString) { _s = aString; }

当要更改每个对象的_s字符串变量的默认值时,您可以调用sets():

ob.SetS("A new string");

您可以使用get()方法检索_s变量的值:

textBox1.Text = ob.GetS();

Classes, Objects, and Methods

Let’s quickly summarize the essential details of classes, objects, and methods. A ‘class’ is the blueprint for an object. It defines the data an object contains and the way it behaves. The following is a very simple C# class to define a Car:

class Car { private string _name; private int _speed; }

在现实世界中,您无法驾驶汽车的蓝图。有人必须从蓝图提供的定义中构建可用的汽车。在C#程序中,我们需要从汽车类提供的定义中创建一个可用的汽车对象。

构造对象

Whenever we construct a new Car object, it needs to be assigned a name and a speed. In C#, I do that in the constructor method called Car():

class Car { private string _name; private int _speed; public Car() { _name = "Generic Car"; _speed = 0; } }

The constructor assigns default values (“Generic Car” and 0) to the private fields (_name and _speed) of each newly constructed Car object. I can construct numerous different Car objects by calling the constructor after the new keyword and then assigning each new Car object to a Car variable. Here I create three Car objects:

Car car1; Car car2; Car car3; car1 = new Car(); car2 = new Car(); car3 = new Car();

This is the programmatic equivalent of constructing three cars from a single blueprint. Having constructed some Car objects, I now want to change their default names and speeds. I can do that using methods. Remember that a ‘method’ is just the object-oriented word to describe a function or subroutine defined inside a class. These are my methods to change (to get and to set) the speed of a Car object:

民众int GetSpeed() { return _speed; } public void SetSpeed(int aSpeed) { _speed = aSpeed; }

I can call a method by writing the name of an object, followed by a dot, the name of a method and a pair of parentheses (with any arguments – that is, the data to be sent to the constructor) and a semicolon, like this:

car1.setspeed(80);car2.setspeed(120);car3.setspeed(100);

继承

继承is one of the key features of object-orientation. The idea is that you create a simple class, then define more specialized classes that inherit all the features of that class and add on additional features of their own. That means you don’t have to recode the same features repeatedly. Features of ‘ancestor’ classes are automatically ‘inherited’ by descendant classes.

For example, you could create a ‘family tree’ of Car classes. A SportsCar might inherit all the features of a Car but add on two extra features: TurboThruster and GoFasterStripe. Another class called LuxuryCar might also descend from the Car class. It would add on the additional features: DeluxeUpholstery and IntegralCocktailCabinet.

Class Hierarchies

To create a descendant of a class, you need to put a colon : plus the ancestor class (or ‘base class’) name after the name of the descendant class, like this:

公共阶级宝藏:事物

后代类继承其祖先的特征(方法和变量),因此您无需重新编码它们。这是您可能为游戏编写的一些C#代码。它定义了一个名为“事物”的基类,并从事物班级下降的宝藏类别:

公共类东西{private string _name;私有字符串_Description;公共事物(字符串aname,string adescription){_name = aname;_description = aDescription;}公共字符串名称{get {return _name;}设置{_name = value;}}公共字符串描述{get {return _description;}设置{_description = value;}}}}
公共阶级宝藏:事物{ private double _value; public Treasure(string aName, string aDescription, double aValue) : base(aName, aDescription) { _value = aValue; } public double Value { get { return _value; } set { _value = value; } } }

Here the Thing class has twoprivatevariables, _name and _description (being private, you cannot access them from outside the class) and two民众属性,名称和描述,以访问这些变量。

Properties

Aproperty是一组或两种特殊类型的方法来获取(返回)或设置(分配)变量的值。这是属性的典型定义:

private string _name; public string Name { get { return _name; } set { _name = value; } }

Here _name is private, but Name is public. This means that code outside the class can refer to the Name property but not the _name variable. If you omit the get part of a property, it will be impossible for code outside the class to retrieve the current value of the associated variable. If you omit the set part, it will be impossible for code outside the class to assign a new value to the related variable – in other words, it will be ‘read-only.’

Building A Class ‘Tree’

I can create more than one descendent ‘branch’ from a class. Here, I create a Room class which is also a descendent of Thing so it too inherits Name and Description. It adds on four direction properties (and variables):

公共房间(字符串aname,string aDescription,int an an,int as,int aw,int ane):base(aname,adescription){_n = an;_s = as;_w = aw;_e = ane;} public int n {get {return _n;}设置{_n = value;}} public int s {get {return _s;}设置{_s = value;}} public int w {get {return _w;}设置{_W = value; } } public int E { get { return _e; } set { _e = value; } }

请注意,为了初始化其“超类”的数据(即其直接祖先),宝藏和房间都需要传递物体构造方法所需的参数。在这里,这些是ANAME和ADESCRIPTION参数。在后代类构造函数的参数列表之后,使用基本关键字将它们传递给超级阶级的构造函数,然后是结肠:

民众Treasure(string aName, string aDescription, double aValue)

:base(aName, aDescription)

民众Room(string aName, string aDescription, int aN, int aS, int aW, int anE)

:base(Aname,Adescription)

This diagram represents my ‘class hierarchy’ with the Treasure and Room classes both descending from the Thing class and inheriting Name and Description. Treasure adds Value. Room adds N, S, W and E:

您不仅限于一个继承的“级别”。我可以继续添加房间和宝藏的子类。例如,我可以创建一个从宝藏中下降的武器类。该武器类将继承其超类(宝藏)和所有其他祖先的所有特征(在这里,唯一的其他祖先是事物)。它会notinherit features from classes that are not its ancestors, though (such as Room). So if I create a Weapon class that descends from Treasure, it would inherit Name, Description and Value. I could then add extra features specific to Weapon objects – such as DestructivePower.

In short, Object Orientation Programming in C# gives you the ability to wrap up data and methods using encapsulation and inherit existing classes’ behavior. Used carefully, this allows the programmer to create secure, reliable programs without too much code duplication.

Page Last Updated:April 2022

Top courses in C#

Complete C# Unity Game Developer 3D
Ben Tristem, Rick Davidson, GameDev.tv Team, Gary Pettie
4.7 (35,379)
Bestseller
C# Intermediate: Classes, Interfaces and OOP
Mosh Hamedani
4.5 (29,606)
Bestseller
RPG Core Combat Creator: Learn Intermediate Unity C# Coding
Ben Tristem, Rick Davidson, Sam Pattuzzi, GameDev.tv Team
4.8 (9,990)
Design Patterns in C# and .NET
Dmitri Nesteruk
4.5 (9,491)
Bestseller
Complete C# Masterclass
Denis Panjuta,Denis Panjuta的教程。
4.6 (21,117)
Unity RPG库存系统资产包:幕后
Sam Pattuzzi, GameDev.tv Team, Rick Davidson
4.5 (685)
完整的c#编程课程,初学者擅长t
Robert Gioia
4.3 (511)
C# 10 | Ultimate Guide - Beginner to Advanced | Master class
Web University by Harsha Vardhan
4.6 (1,304)
统一的编程设计模式 - 编写更好的代码
GameDev.tv Team, Sam Pattuzzi
4.6 (400)
单体组:C#游戏编程简介
Kyle Schaub
4.8 (664)
Bestseller
统一C# Scripting : Complete C# For Unity Game Development
Raja Biswas, Charger Games
4.6 (2,061)
Bestseller

More C# Courses

C# students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

请求演示

Huw Collingbourne的课程

初学者的红宝石编程
Huw Collingbourne
4 (741)
Learn C# Programming (In Ten Easy Steps)
Huw Collingbourne
4.3 (1,061)
Learn To Program with Delphi and Object Pascal
Huw Collingbourne
4.6 (682)
Bestseller
Break Into The Programming Business
Huw Collingbourne
3.6 (67)
How to teach an online course
Huw Collingbourne
4.8 (292)
C Programming For Beginners
Huw Collingbourne
4.2 (3,976)
Java Programming – the Master Course
Huw Collingbourne
4.3 (284)
Ruby For Programmers
Huw Collingbourne
4.2 (352)
Advanced C Programming: Pointers
Huw Collingbourne
4.5 (2,663)

Huw Collingbourne的课程