// Calling a custom constructor.
Point pt = new Point(10, 16) { X = 100, Y = 100 };
Given the current definition of our Point type, calling the custom constructor while using ini-
tialization syntax is not terribly useful (and more than a bit verbose). However, if our Point type
provides a new constructor that allows the caller to establish a color (via a custom enumeration
named PointColor), the combination of custom constructors and object initialization syntax
becomes clear. Assume we have updated Point as follows:
public enum PointColor
{ LightBlue, BloodRed, Gold }
public class Point
{
public int xPos, yPos;
private PointColor c;
public Point(PointColor color)
{
xPos = 0; yPos = 0;
c = color;
}
public Point(){}
public Point(int x, int y)
{
xPos = x; yPos = y;
c = PointColor.Gold;
}
...
public override string ToString()
{ return string.Format("[{0}, {1}, Color = {2}]", xPos, yPos, c); }
}
With this new constructor, we can now create a golden point (positioned at 90, 20) as follows:
Do'stlaringiz bilan baham: |