public String Name { get; set { if (name == null || name.Length == 0) return;} } // 赋值name时字符串不能为空
public String ID { get; set; } }
同时,C#中的属性访问器还支持简单的写法:
1 2 3 4 5 6 7 8 9 10
class StudentOne { private string name;
private string ID;
public String Name { get; set; }
public String ID { get; set; } }
1 2 3 4 5 6
class StudentTwo { public String Name { get; set; }
public String ID { get; set; } }
比如说这上面两个写法是等效的,下面的写法实际上也会创建一个私有字段:
1 2 3 4 5 6 7 8 9 10
class Program { public static void Main(string[] args) { Person person = new Person(); Console.WriteLine(person.Name); person.Name = "阿巴阿巴"; Console.WriteLine(person.Name); } }
1 2 3 4 5
public class Person { private string name = "诶嘿诶嘿"; public string Name { get { return name; } set { name = value; } } }
1 2 3 4
public class Person { public string Name { get; set; } = "诶嘿诶嘿"; }