1/10/2014
3:06:00 PM 0

C# Class and Struct

1.Memory Allocation

Class => Reference Type
Struct => Value Type

new operator on a class => heap
instantiate a struct => stack

以上的差異造成傳遞資料到 method 中會有不同的結果

Class => a reference is passed
Struct => a copy of the struct is passed

以下引用 MSDN 的範例程式 http://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx
// struct2.cs
using System;

class TheClass
{
    public int x;
}

struct TheStruct
{
    public int x;
}

class TestClass
{
    public static void structtaker(TheStruct s)
    {
        s.x = 5;
    }
    public static void classtaker(TheClass c)
    {
        c.x = 5;
    }
    public static void Main()
    {
        TheStruct a = new TheStruct();
        TheClass b = new TheClass();
        a.x = 1;
        b.x = 1;
        structtaker(a);
        classtaker(b);
        Console.WriteLine("a.x = {0}", a.x);
        Console.WriteLine("b.x = {0}", b.x);
    }
}
Struct傳遞的是複本, 所以結果 a.x = 1, 而 b.x = 5

2.Constructors

Struct 不可使用無參數的constructor ,結構成員也不可設定初始值, 也不可使用 destructor

錯誤
public struct TheStruct1
{
    public TheStruct1()
    {      
    }
    public int x = 0;
}
正確
public struct TheStruct1
{
    public TheStruct1(int c)
    {
        x = c;
    }
    public int x;
}
TheStruct1 a = new TheStruct1();
Console.WriteLine("a.x = {0}", a.x);
TheStruct1 b = new TheStruct1(2);
Console.WriteLine("b.x = {0}", b.x);
TheStruct1 c = default(TheStruct1);//use default keyword
Console.WriteLine("c.x = {0}", c.x);
TheStruct1 d;
d.x = 99;//Initialize
Console.WriteLine("d.x = {0}", d.x);
當執行個體化結構且建構子未傳入值時,結構成員會自動初始化

執行結果
a.x = 0
b.x = 2
c.x = 0
d.x = 99

3.Inheritance

結構沒有繼承,但可實作介面

4.自訂結構在記憶體中的安排方式

使用 StructLayout(LayoutKind.Union) 和 FieldOffset

5.使用時機

struct被定義為輕量化的物件,與物件相比較 struct GC 的成本小,微軟建議在下面的狀況下可考慮使用struct

√ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
X AVOID defining a struct unless the type has all of the following characteristics:
  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.
引用自 http://msdn.microsoft.com/en-us/library/ms229017.aspx

參考
Structs  http://msdn.microsoft.com/en-us/library/saxz13w4.aspx
Classes and Structs  http://msdn.microsoft.com/en-us/library/ms173109.aspx
Class and struct differences  http://msdn.microsoft.com/en-us/library/aa664471(v=vs.71).aspx

0 comments:

Post a Comment