C#中set、get用法
在面向对象编程(OOP)中,用户只需要知道对象(object)能做什么,而不需要知道其如何完成的,或者说不允许访问其内部,这体现了面向对象的3个基本原则中的封装。
面向对象的基本原则: 封装(Encapsulation) 多态(Polymorphism) 继承(Inheritance)
一般来说,域是私有的(域表示存储位置,域的类型可以是c#中的任何数据类型)。对所有有必要在类外可见的域,C#推荐采用属性来表达。属性提供了只读(get),只写(set),读写(get和set)三种接口操作。对域的这三种操作,必须在同一个属性名下声明,而不可以将它们分离。
public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;
// this is a property. When you access it uses the underlying field, but only exposes
// the contract that will not be affected by the underlying field
public string MyField
get
return _myField;
}
set
_myField = value;
当引用属性时,除非该属性为赋值目标,否则将调用 get 访问器读取该属性的值。(这里解释程序是如何判别应该调用get还是set的)
2、使用set和get的好处
为赋值与取值增加控制
保证属性的安全性,不能直接修改域
便于维护,可实现在set访问器中一处更改
3、自动属性(Auto-Implemented Properties)
自动属性是C# 3.0新语言特性和改进
以下两种代码等效
public class Student
public string Name { get; set; }
private string name; // This is the so-called "backing field"
public string Name // This is your property
get {return name;}
set {name = value;}
在C#6中可以赋初值:public string text
get;
set;
} = "小二狗";
参考:https://www.jianshu.com/p/00bea9f0209a
友情链接
搜狐、网易、新浪、赶集