当初始化类的对象时,如果有多个属性,考虑到每一种组合的话需要定义很多构造器,显然这是很麻烦的,通过对象初始化器可以很好地解决这个问题
- 在类中对字段初始化;
- 创建对象的时候使用对象初始化器;
1 //在创建类的时候对其属性进行初始化 2 class Polygon 3 { 4 public int NumSides { get; set; } 5 public double SideLength { get; set; } 6 public Polygon() 7 { 8 this.NumSides = 4; 9 this.SideLength = 10.0; 10 } 11 } 12 //在创建对象时使用对象初始化器 13 static void DoWork() 14 { 15 // to do 16 Polygon square = new Polygon(); 17 Polygon triangle = new Polygon { NumSides = 3 }; 18 Polygon pentagon = new Polygon { SideLength = 15.5, NumSides = 5 }; 19 Console.WriteLine("Square: number of sides is {0},length of each side is {1}",square.NumSides,square.SideLength); 20 Console.WriteLine("triangle: number of sides is {0},length of each side is {1}", triangle.NumSides, triangle.SideLength); 21 Console.WriteLine("pentagon: number of sides is {0},length of each side is {1}", pentagon.NumSides, pentagon.SideLength); 22 } 23 24 static void Main(string[] args) 25 { 26 try 27 { 28 DoWork(); 29 } 30 catch (Exception ex) 31 { 32 Console.WriteLine(ex.Message); 33 } 34 }
时间: 2024-10-09 12:47:37