Structs 和 Classes 的比較
| Structs | Classes |
|---|---|
| Value type | Refrence type |
| 記憶體中為 stack | 記憶體中為 heap |
| 不支援 null | 支援 null |
MSDN Structs 限制
- 結構宣告內不能初始化欄位,除非將其宣告為 const 或 static。
- 結構不可宣告預設建構函式 (沒有參數的建構函式) 或解構函式。
- 結構是在指派時複製的。 當指派結構給新變數時,就會複製所有資料,而新變數所做的任何修改都不會變更原始複本的資料。 在使用如 Dictionary 的實際型別集合時,請務必謹記這一點。
- 結構為實值型別,而類別則是參考型別。
- 與類別不同的是,結構並不需要使用 new 運算子就能具現化。
- 結構可以宣告含有參數的建構函式。
- 結構無法從另一個結構或類別繼承而來,且它不能成為類別的基底。 所有結構都是從繼承自 System.Object 的 System.ValueType 直接繼承而來
- 結構可實作介面
- 結構可以用來當做可為 Null 的型別,而且可以對其指派 null 值。
此 MVA 範例說明 Structs 和 Classe 在 Value type 和 Refrence type 的差異
namespace MVATwentyQuestions
{
class Program
{
public struct PointStruct
{
public int x;
public int y;
public PointStruct(int x, int y)
{
this.x = x;
this.y = y;
}
}
class PointClass
{
public int x;
public int y;
public PointClass(int x, int y)
{
this.x = x;
this.y = y;
}
}
static void Main(string[] args)
{
PointStruct structPoint = new PointStruct();
structPoint.x = 10;
structPoint.y = 10;
Console.WriteLine("Initial struct values are " + structPoint.x + ", " + structPoint.y);
ModifyStructPoint(structPoint);
Console.WriteLine("After ModifyStructPoint, struct values are " + structPoint.x + ", " + structPoint.y);
Console.WriteLine();
PointClass classPoint = new PointClass(10, 10);
Console.WriteLine("Initial class values are " + classPoint.x + ", " + classPoint.y);
ModifyClassPoint(classPoint);
Console.WriteLine("After ModifyClassPoint, class values are " + classPoint.x + ", " + classPoint.y);
}
static void ModifyStructPoint(PointStruct newStruct)
{
newStruct.x = 20;
newStruct.y = 20;
Console.WriteLine("Inside ModifyStructPoint()");
Console.WriteLine("Modified values are " + newStruct.x + ", " + newStruct.y);
}
static void ModifyClassPoint(PointClass newPoint)
{
newPoint.x = 20;
newPoint.y = 20;
Console.WriteLine("Inside ModifyClassPoint()");
Console.WriteLine("Modified values are " + newPoint.x + ", " + newPoint.y);
}
}
}
![[C#] Structs VS Classes](https://farm6.staticflickr.com/5498/14170026788_9eaf6ba3f4_o.jpg)
沒有留言:
張貼留言