现在的位置: 首页 > 综合 > 正文

构造函数总结

2012年12月29日 ⁄ 综合 ⁄ 共 799字 ⁄ 字号 评论关闭
构造函数总结

1:构造方法要与类名相同
2:构造函数无返回值
3:对对象进行初始化 ,且默认为0或null。
4 :构造函数的声明为public类型,不可以声明protected成员、virtual成员、sealed成员和override成员;
5:可以重载System.Object的3个虚方法,Equals()、ToString()和GetHashTable()。
6:也不能声明抽象函数。
7:没有void修饰。

class CoOrds//类名
{
    public int x, y;

    // Default constructor:
    public CoOrds()
    {
        x = 0;//初始化 
        y = 0;
    }

    // A constructor with two arguments:
    public CoOrds(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    // Override the ToString method:
    public override string ToString()
    {
        return (System.String.Format("({0},{1})", x, y));
    }
}

class MainClass
{
    static void Main()
    {
        CoOrds p1 = new CoOrds();
        CoOrds p2 = new CoOrds(5, 3);

        // Display the results using the overriden ToString method:
        System.Console.WriteLine("CoOrds #1 at {0}", p1);
        System.Console.WriteLine("CoOrds #2 at {0}", p2);
    }
}

抱歉!评论已关闭.