一、結構和類的區別
1、結構的級別和類一致,寫在命名空間下面,可以定義字段、屬性、方法、構造方法也可以通過關鍵字new創建對象。
2、結構中的字段不能賦初始值。
3、無參數的構造函數無論如何C#編譯器都會自動生成,所以不能為結構定義一個無參構造函數。
4、在構造函數中,必須給結構體的所有字段賦值。
5、在構造函數中,為屬性賦值,不認為是對字段賦值,因為屬性不一定是去操作字段。
6、結構是值類型,在傳遞結構變量的時候,會將結構對象里的每一個字段復制一份拷貝到新的結構變量的字段中。
7、不能定義自動屬性,因為字段屬性會生成一個字段,而這個字段必須要求在構造函數中,但我們不知道這個字段叫什么名字。
8、聲明結構體對象,可以不使用new關鍵字,但是這個時候,結構體對象的字段沒有初始值,因為沒有調用構造函數,構造函數中必須為字段賦值,所以,通過new關鍵字創建結構體對象,這個對象的字段就有默認值。
9、棧的訪問速度快,但空間小,堆的訪問速度慢,但空間大,當我們要表示一個輕量級的對象的時候,就定義為結構,以提高速度,根據傳至的影響來選擇,希望傳引用,則定義為類,傳拷貝,則定義為結構。
二、Demo
public int X
{
get { return x; }
set { x = value; }
}
private int y;
public int Y
{
get { return y; }
set { y = value; }
}
public void Show()
{
Console.Write("X={0},Y={1}", this.X, this.Y);
}
public Point(int x,int y)
{
this.x = x;
this.y = y;
this.p = null;
}
public Point(int x)
{
this.x = x;
this.y = 11;
this.p = null;
}
public Point(int x, int y, Program p)
{
this.x = x;
this.y = y;
this.p = p;
}
}
class Program
{
public string Name { get; set; }
static void Main(string[] args)
{
//Point p = new Point();
//p.X = 120;
//p.Y = 100;
//Point p1 = p;
//p1.X = 190;
//Console.WriteLine(p.X);
//Point p;
//p.X = 12;//不賦值就會報錯
//Console.WriteLine(p.X);
//Point p1 = new Point();
//Console.WriteLine(p1.X);//此處不賦值不會報錯,原因見區別8
Program p = new Program() { Name="小花"};
Point point1 = new Point(10, 10, p);
Point point2 = point1;
point2.p.Name = "小明";
Console.WriteLine(point1.p.Name);//結果為小明,分析見下圖
}
}
新聞熱點
疑難解答