|
构造函数与析构函数:using System;
class MyClass
{
private int FNum;
public int Num { get { return FNum; } }
/* 构造函数没有返回值, 无参的构造函数是默认的 */
public MyClass()
{
this.FNum = 2009;
}
/* 可以有多个参数不同的构造函数 */
public MyClass(int x)
{
this.FNum = x;
}
public MyClass(params int[] arr)
{
foreach (int i in arr) this.FNum += i;
}
/* 析构函数无参、无返回值、无访问修饰, 最多只能有一个 */
~MyClass()
{
//析构函数是自动调用的
}
}
class Program
{
static void Main()
{
MyClass obj1, obj2, obj3;
obj1 = new MyClass();
Console.WriteLine(obj1.Num); //2009
obj2 = new MyClass(100);
Console.WriteLine(obj2.Num); //100
obj3 = new MyClass(1, 2, 3);
Console.WriteLine(obj3.Num); //6
Console.ReadKey();
}
}using System;
class MyClass
{
private MyClass() { }
public static void Msg1() { Console.WriteLine("Msg1"); }
public static void Msg2() { Console.WriteLine("Msg2"); }
}
class Program
{
static void Main()
{
MyClass.Msg1(); //Msg1
MyClass.Msg2(); //Msg2
Console.ReadKey();
}
}
如果一个类有了非默认的构造函数, 就不能再使用默认的构造函数:using System;
class MyClass
{
private int FNum;
public int Num { get { return FNum; } }
public MyClass(int x, int y)
{
this.FNum = x + y;
}
}
class Program
{
static void Main()
{
MyClass obj;
obj = new MyClass(1, 2);
Console.WriteLine(obj.Num); //3
Console.ReadKey();
}
}
|
|