写法1:
使用private字段,然后给public字段设置set and get,这样可以直接给私有字段一个默认值(这个赋值操作可以直接给私有字段,也可以在公共字段的get方法中判断私有字段是否为空,然后给默认值),具体写法不再赘述,不会的可以问下度娘,或参考我的博问:
缺点:写法不够优美,代码冗余,到处都是set, get之类的
写法2:
在无参构造函数中给共有字段1个默认值,即赋值操作。由于使用对象初始化器的写法可以先调用无参构造函数,因此在大括号中的内容被调用时,其实各个属性均已被赋值.
对象初始化器可以加小括号,也可以不加小括号,直接跟上1个大括号即可。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleApplication15 7 { 8 class Program 9 { 10 public class Cell { 11 private int _id; 12 public int ID { 13 get { 14 return _id; 15 } 16 set { 17 Console.WriteLine("为ID赋值"); 18 _id = value; 19 } 20 } 21 public string Name; 22 23 public Cell() { 24 Console.WriteLine("Cell构造函数"); 25 this.ID = 1; 26 this.Name = "小明"; 27 } 28 } 29 30 static void Main(string[] args) 31 { 32 Print(new Cell{ 33 ID = 3 34 }); 35 } 36 37 static void Print(Cell c) { 38 Console.WriteLine(c.ID); 39 Console.WriteLine(c.Name); 40 } 41 } 42 }
1. 说明先调用无参数构造函数.jpg
也可以使用对象初始化器给对象赋值,再调用大括号内的赋值,只需将以上代码中Cell添加构造函数:
1 public Cell(int _aid) { 2 Console.WriteLine("Cell 有1个参数的构造函数"); 3 this.ID = _aid; 4 }
在main函数调用处修改为:
1 static void Main(string[] args) 2 { 3 Print(new Cell(1){ 4 ID = 3 5 }); 6 }
结果如图:
<完>