官术网_书友最值得收藏!

Properties

For security reasons, all the fields of a class shouldn't be exposed to the outside world. Consequently, exposing private fields is done by properties in C#, which are members of that class. Underneath the properties are special methods that are called accessors. A property contains two accessors: get and set. The get accessor gets values from the field while the set accessor sets values to the field. There is a special keyword for a property, named value. This represents the value of a field.

By using access modifiers, properties can have different access levels. A property can be public, privateread only, open for read and write, and write only. If only the set accessor is implemented, this means that the only write permission is given. If both set and get accessors are implemented, this means that both read and write permissions are open for that property.

C# provides a smart way of writing setter and getter methods. If you create a property in C#, you don't have to manually write setter and getter methods for a particular field. Consequently, the common practice in C# is to create properties in a class, rather than creating fields and setter and getter methods for those fields.

Let's take a look at how to create property in C#, as shown in the following code:

class Animal {
public string Name {set; get;}
public int Age {set; get;}
}

The Animal class has two properties: Name and Age. Both the properties have Public access modifiers as well as setter and getter methods. This means that both properties are open for read and write operations. The convention is that properties should be in camel case.

If you want to modify your set and get methods, you can do so in the following way:

class Animal {
public string Name {
set {
name = value;
}
get {
return name;
}
}
    public int Age {set; get;}
}

In the preceding example, we are not using the shortcut of creating setters and getters for the Name property. We have extensively written what the set and get methods should do. If you look closely, you will see the name field in lowercase. This means that when you create a property in camel case, a field with the same name is created internally, but in Pascal case. The value is a special keyword that actually represents the value of that property.

Properties are working behind the scenes in the background, which makes the code much cleaner and easier to use. It's very much recommended that you use properties instead of local fields.

主站蜘蛛池模板: 大渡口区| 丘北县| 科技| 福泉市| 柯坪县| 金昌市| 兴安县| 喜德县| 东宁县| 安仁县| 通江县| 大邑县| 浠水县| 定兴县| 龙陵县| 通河县| 泸水县| 黄山市| 定州市| 潢川县| 榆中县| 台州市| 永寿县| 湖口县| 克山县| 涟源市| 万山特区| 五家渠市| 江都市| 仁化县| 峡江县| 常宁市| 甘洛县| 高雄市| 东阳市| 贵溪市| 兰溪市| 濉溪县| 宝山区| 三明市| 弋阳县|