C#3.0中加入的对象构造者特性,使得对象的初始化工作变得格外简单,我们可以采用类似于数组初始化的方式来初始化类的对象,方法就是直接在创建类对象的表达式后面跟上类成员的初始化代码。
以前我们在声明数组时,可以同时对其进行初始化,这样就省去了很多麻烦,但是在创建类的对象时,这招可就不灵了,我们要么调用该类的构造函数完成对象的初始化,要么就手工进行初始化。这两种方法都不太方便,使用构造函数来对对象进行初始化时,我们为了某种灵活性,可能需要编写构造函数的多个重载版本,实在是麻烦。
具体示例如下:
class Point
{
public int X { get; set; }
public int Y { get; set; }
public override string ToString()
{
return "(" + X.ToString() + ", " + Y.ToString() + ")";
}
}
class Rectangle
{
public Point P1 { get; set; }
public Point P2 { get; set; }
public Rectangle()
{
P1 = new Point();
P2 = new Point();
}
public override string ToString()
{
return "P1: " + P1 + ", P2: " + P2;
}
}
class ObjectBuilder : AppRunner.AbstractApplication
{
public override void Run()
{
Point thePoint = new Point() { X = 1, Y = 2 };
Console.WriteLine("Point(X, Y) = {0}", thePoint);
Rectangle theRectangle = new Rectangle() {
P1 = { X = 1, Y = 1 }, P2 = { X = 100, Y = 200 }
};
Console.WriteLine(theRectangle);
}
}
赞
If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)
QQ:154298438
QQ:417480759