C#3.0语言新特性之对象和集合初始化器
2009-03-11 08:19:23 来源:WEB开发网现在,我们来测试如下代码:
class Program
{
static void Main()
{
Point p = new Point(PointColor.黑色) { X = 100, Y = 200 };
Point p1 = new Point(10, 20) { X = 100, Y = 200 };
Console.WriteLine(p);
Console.WriteLine(p1);
}
}
最后程序运行的结果为:
[100,200,Color=黑色]
[100,200,Color=绿色]
20.4.3 初始化内部类型
我们来看这样一个实际例子。我们需要定义一个Rectangle类,使用Point类型来代表左上角和右下角两个点的坐标,代码如下所示:
public class Rectangle
{
private Point topLeft = new Point();
private Point bottomRight = new Point();
public Point TopLeft
{
get { return topLeft; }
set { topLeft = value; }
}
public Point BottomRight
{
get { return bottomRight; }
set { bottomRight = value; }
}
public override string ToString()
{
return string.Format("[TopLeft: {0}, {1}, BottomRight: {2}, {3}]",
topLeft.X, topLeft.Y, bottomRight.X, bottomRight.Y);
}
}
更多精彩
赞助商链接