C#构造函数实例

在此示例中,类 Person 没有任何构造函数;在这种情况下,将自动提供默认构造函数,同时将字段初始化为它们的默认值。

public class Person
{
    public int age;
    public string name;
}

class TestPerson
{
    static void Main()
    {
        Person p = new Person();

        System.Console.Write("Name: {0}, Age: {1}", p.name, p.age);
    }
}

下面的示例说明包含两个类构造函数的类:一个类构造函数没有参数,另一个类构造函数带有两个参数

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);
    }
}

posted on 2007-04-07 21:17  shengel  阅读(321)  评论(0)    收藏  举报