.NET中struct與class的區別

來源:互聯網
上載者:User

標籤:.net   struct   class   實值型別   參考型別   

在.net中的struct與class有很多相似之處,比如可以直接new,對於成員可以直接XX.field,以至於有不少程式員在用時,將其混在一起,分不清有何區別。這兩者有何區別呢?

1.類型不同

我們先來看一段代碼

  static void Main(string[] args)        {            TypeDemo();                       Console.ReadLine();        }        // Reference type (because of 'class')         class SomeClassRef { public Int32 x; }        // Value type (because of 'struct')         struct SomeStructVal { public Int32 x; }        static void TypeDemo()        {            SomeClassRef r1 = new SomeClassRef(); // Allocated in heap             SomeStructVal v1 = new SomeStructVal(); // Allocated on stack             r1.x = 5; // Pointer dereference             v1.x = 5; // Changed on stack             Console.WriteLine("r1=" + r1.x.ToString()); // Displays "5"             Console.WriteLine("v1=" + v1.x.ToString()); // Also displays "5"             // The left side of Figure 5­2 reflects the situation             // after the lines above have executed.             SomeClassRef r2 = r1; // Copies reference (pointer) only             SomeStructVal v2 = v1; // Allocate on stack & copies members             r1.x = 8; // Changes r1.x and r2.x             v1.x = 9; // Changes v1.x, not v2.x             Console.WriteLine("r1=" + r1.x.ToString()); // Displays "8"             Console.WriteLine("r2=" + r2.x.ToString()); // Displays "8"             Console.WriteLine("v1=" + v1.x.ToString()); // Displays "9"             Console.WriteLine("v2=" + v2.x.ToString()); // Displays "5"             // The right side of Figure 5­2 reflects the situation             // after ALL of the lines above have executed.         }
該代碼執行結果如下


從代碼中,我們可以看到,r1和v1都是new出來的,同時其欄位x都賦值為5.所以輸出的是r1=5,v1=5。

接著又定義了r2和v2,並將r2賦值為r1,v2賦值為v1。之後,將欄位x分別賦值為8和9,接緊接著輸出各自的x。結果是r1和r2的x值相同,都變成了後來賦值的8。v1和v2的x值不一樣,r1是第一次賦值的5,r2是後面賦值的9.

那引起這種差異的原因是什麼呢?我們先用IL來查看一下產生的EXE。


從IL中我們可以看到,SomeClassRef是繼承自System.Object,是Object,是參考型別。SomeStructVal是繼承自System.ValueType,是值類型。

也就是說class是參考型別,struct是值類型。

參考型別得到的是地址(或者是指標),這樣在r2=r1的賦值過程中,其實是將r1的地址賦給了r2,所以r1和r2指向的其實指向的是同一個對象。而對象是儲存在heap中。

值類型是直接存在Thread Statck中。在r2=r1的賦值過程中,是直接的記憶體資料拷貝。

簡單的說,參考型別的賦值,始終只有一個對象,一個資料存放區空間。值類型的賦值,賦值幾次就有幾個對象,幾個儲存空間。可以參看。


在ThreadStatck中儲存著r1、r2、v1、v2。r1和r2指向的是Managed Heap中的object。而v1和v2始終在Thread Statck中,其欄位x是緊接v1或v2之後。

2.函數傳參影響不同

我們常見的基本類型如Int32、bool、byte等都是值類型,都具有相同的特性。因為值類型的賦值是資料拷貝,參考型別是引用拷貝,所以兩者在作為函數參數傳傳遞時就會有很大的差異。值類型作參數的,其原始值不會受影響,而參考型別作參數的,其原始值會受影響。測試代碼如下

  static void Main(string[] args)        {                      TestFunc();            Console.ReadLine();        }  static void TestFunc()        {            SomeClassRef r = new SomeClassRef();            r.x = 1;            SomeStructVal v = new SomeStructVal();            v.x = 1;            RefFunc(r);            ValFunc(v);            Console.WriteLine(r.x);            Console.WriteLine(v.x);        }        static void RefFunc(SomeClassRef r)        {            r.x = 100;        }        static void ValFunc(SomeStructVal v)        {            v.x = 100;        }


從結果可以看到,r為class,為參考型別,在經過RefFunc函數後,其欄位x的值變成了100。v為struct,為值類型,在經過ValFunc後,其欄位x的值仍然為原始值1.

3.繼承性不同

class可以繼承,struct不可以繼承。


可以看到,SomeStructValChild繼承SomeStructVal,編譯無法通過。提示說無法從密封類型中派生。這麼看來,struct被當成了密封類型。其實所有的值類型都是密封(sealed)類型。比如Boolean, Char, Int32, UInt64, Single, Double, Decimal。大家可以參看一下《CLR via C# 第四版》中的一段原文:


有人會說,這裡是用class來繼承SomeStructVal的,一個是class,一個是struct,兩者不一樣,當然不能繼承。那我們試試struct。


同樣編譯不能通過,提示說SomeStructVal不是介面。

當然除了繼承性這樣類的特性外,還有很多類的特性在struct中也是不可以使用的。比如類的虛方法、重載等。

4.GC的觸發

從前面的圖中,我們可以看到,SomeClassRef是在Managed Heap中開闢了一塊空間來儲存,而在Managed Headp開闢了空間,就必然會觸發記憶體回收(GC)。在Thread Statck中則不會觸發GC。

所以如果不斷的去new一個SomeClassRef和new一個SomeStructVal,兩者的耗時會有很大的差距。可以推測,SomeStructVal的時間肯定會少於SomeClassRef。下面是測試代碼

  private const int TIME_MAX = 100000000;        static void Main(string[] args)        {                      TestStruct();            TestClass();                     Console.ReadLine();        } static void TestStruct()        {            Stopwatch sw = new Stopwatch();            sw.Start();            for (int i = 0; i < TIME_MAX; i++)            {                SomeStructVal v1 = new SomeStructVal();                v1.x = i;            }            sw.Stop();            Console.WriteLine("Struct time:" + sw.ElapsedMilliseconds.ToString());        }        static void TestClass()        {            Stopwatch sw = new Stopwatch();            sw.Start();            for (int i = 0; i < TIME_MAX; i++)            {                SomeClassRef r1 = new SomeClassRef();                r1.x = i;            }            sw.Stop();            Console.WriteLine("Class time:" + sw.ElapsedMilliseconds.ToString());        }

測試結果見


可以看到,class的時間消耗是struct的3倍多。當然這裡的耗時還有class在Managed Headp中開闢空間時需要引使用者指標(Type object ptr)和同步塊索引(Sync block Index)。

5.裝箱與拆箱

對於值類型,如果要轉換成Object,會有一個裝箱(box),再從Object轉換成值類型時,會有一個拆箱的操作。而對於參考型別,則沒有裝箱和拆箱的過程。這也就引出了struct和class的裝箱和拆箱的差別。下面是測試代碼

 static void BoxAndUnbox_struct()        {            ArrayList a = new ArrayList();            SomeStructVal v; // Allocate a SomeStructVal (not in the heap).             for (Int32 i = 0; i < 10; i++)            {                v = new SomeStructVal();                v.x = i; // Initialize the members in the value type.                 a.Add(v); // Box the value type and add the                 // reference to the Arraylist.             }            SomeStructVal v2 = (SomeStructVal)a[0];            Console.WriteLine(v2.x);        }        static void BoxAndUnbox_class()        {            ArrayList a = new ArrayList();            SomeClassRef r; // Allocate SomeClassRef in the heap.             for (Int32 i = 0; i < 10; i++)            {                r = new SomeClassRef();                r.x = i; // Initialize the members in the value type.                 a.Add(r); //add the reference to the Arraylist.             }            SomeClassRef r2 = (SomeClassRef)a[0];            Console.WriteLine(r2.x);                  }

編譯後,使用IL查看EXE

BoxAndUnbox_class函數

.method private hidebysig static void  BoxAndUnbox_class() cil managed{  // 代碼大小       75 (0x4b)  .maxstack  2  .locals init ([0] class [mscorlib]System.Collections.ArrayList a,           [1] class ClassAndStruct.Program/SomeClassRef r,           [2] int32 i,           [3] class ClassAndStruct.Program/SomeClassRef r2,           [4] bool CS$4$0000)  IL_0000:  nop  IL_0001:  newobj     instance void [mscorlib]System.Collections.ArrayList::.ctor()  IL_0006:  stloc.0  IL_0007:  ldc.i4.0  IL_0008:  stloc.2  IL_0009:  br.s       IL_0026  IL_000b:  nop  IL_000c:  newobj     instance void ClassAndStruct.Program/SomeClassRef::.ctor()  IL_0011:  stloc.1  IL_0012:  ldloc.1  IL_0013:  ldloc.2  IL_0014:  stfld      int32 ClassAndStruct.Program/SomeClassRef::x  IL_0019:  ldloc.0  IL_001a:  ldloc.1  IL_001b:  callvirt   instance int32 [mscorlib]System.Collections.ArrayList::Add(object)  IL_0020:  pop  IL_0021:  nop  IL_0022:  ldloc.2  IL_0023:  ldc.i4.1  IL_0024:  add  IL_0025:  stloc.2  IL_0026:  ldloc.2  IL_0027:  ldc.i4.s   10  IL_0029:  clt  IL_002b:  stloc.s    CS$4$0000  IL_002d:  ldloc.s    CS$4$0000  IL_002f:  brtrue.s   IL_000b  IL_0031:  ldloc.0  IL_0032:  ldc.i4.0  IL_0033:  callvirt   instance object [mscorlib]System.Collections.ArrayList::get_Item(int32)  IL_0038:  castclass  ClassAndStruct.Program/SomeClassRef  IL_003d:  stloc.3  IL_003e:  ldloc.3  IL_003f:  ldfld      int32 ClassAndStruct.Program/SomeClassRef::x  IL_0044:  call       void [mscorlib]System.Console::WriteLine(int32)  IL_0049:  nop  IL_004a:  ret} // end of method Program::BoxAndUnbox_class
可以看到,IL代碼中沒有一個box或unbox的操作,只有pop一類的操作。可以判定並沒有進行裝箱和拆箱。

再來看BoxAndUnbox_struct函數

.method private hidebysig static void  BoxAndUnbox_struct() cil managed{  // 代碼大小       84 (0x54)  .maxstack  2  .locals init ([0] class [mscorlib]System.Collections.ArrayList a,           [1] valuetype ClassAndStruct.Program/SomeStructVal v,           [2] int32 i,           [3] valuetype ClassAndStruct.Program/SomeStructVal v2,           [4] bool CS$4$0000)  IL_0000:  nop  IL_0001:  newobj     instance void [mscorlib]System.Collections.ArrayList::.ctor()  IL_0006:  stloc.0  IL_0007:  ldc.i4.0  IL_0008:  stloc.2  IL_0009:  br.s       IL_002e  IL_000b:  nop  IL_000c:  ldloca.s   v  IL_000e:  initobj    ClassAndStruct.Program/SomeStructVal  IL_0014:  ldloca.s   v  IL_0016:  ldloc.2  IL_0017:  stfld      int32 ClassAndStruct.Program/SomeStructVal::x  IL_001c:  ldloc.0  IL_001d:  ldloc.1  IL_001e:  box        ClassAndStruct.Program/SomeStructVal  IL_0023:  callvirt   instance int32 [mscorlib]System.Collections.ArrayList::Add(object)  IL_0028:  pop  IL_0029:  nop  IL_002a:  ldloc.2  IL_002b:  ldc.i4.1  IL_002c:  add  IL_002d:  stloc.2  IL_002e:  ldloc.2  IL_002f:  ldc.i4.s   10  IL_0031:  clt  IL_0033:  stloc.s    CS$4$0000  IL_0035:  ldloc.s    CS$4$0000  IL_0037:  brtrue.s   IL_000b  IL_0039:  ldloc.0  IL_003a:  ldc.i4.0  IL_003b:  callvirt   instance object [mscorlib]System.Collections.ArrayList::get_Item(int32)  IL_0040:  unbox.any  ClassAndStruct.Program/SomeStructVal  IL_0045:  stloc.3  IL_0046:  ldloca.s   v2  IL_0048:  ldfld      int32 ClassAndStruct.Program/SomeStructVal::x  IL_004d:  call       void [mscorlib]System.Console::WriteLine(int32)  IL_0052:  nop  IL_0053:  ret} // end of method Program::BoxAndUnbox_struct
可以看到在ArrayList的add方法時,有一個box的操作,然後再pop進去。

這裡是因為ArrayList的Add方法是針對object的,而SomeStructVal是值類型,所以必須裝箱成object,然後再add進去。

在裝箱時,值類型會依據ThreadStack中的該值所佔的控制項在Managed Heap中開闢相應的空間,並裝資料拷貝進去(頭部還會增加Type ojbect Ptr和Sync block Index)。

這在無形中就增加了空間的消耗,所以使用ArrayList等需要將值類型進行裝箱的操作,必須加以考量。當然ArrayList一般可以用List<T>來代替。在泛型(<T>)的List中,直接針對的是T類型,所以如果List的泛型T是值類型,將不會有裝箱的操作,可以認為是直接在ThreadStack中開闢空間存資料。

由於有了裝箱,所以在拿ArrayList的資料時,必然需要拆箱。

需要注意的是,拆箱並不是簡單的引用Managed Heap中的資料,而是將該資料拷貝到了Thread Stack中。所以兩者已經不是一個對象了。

下面是測試代碼

 static void Unbox()        {            SomeStructVal v = new SomeStructVal();            v.x = 1;            Object o = v;            SomeStructVal v2 = (SomeStructVal)o;            v2.x = 11;            SomeStructVal v3 = (SomeStructVal)o;            Console.WriteLine("v2.x="+v2.x.ToString());            Console.WriteLine("o.x="+v3.x.ToString());        }

結果如


下面是IL的代碼

.method private hidebysig static void  Unbox() cil managed{  // 代碼大小       104 (0x68)  .maxstack  2  .locals init ([0] valuetype ClassAndStruct.Program/SomeStructVal v,           [1] object o,           [2] valuetype ClassAndStruct.Program/SomeStructVal v2,           [3] valuetype ClassAndStruct.Program/SomeStructVal v3)  IL_0000:  nop  IL_0001:  ldloca.s   v  IL_0003:  initobj    ClassAndStruct.Program/SomeStructVal  IL_0009:  ldloca.s   v  IL_000b:  ldc.i4.1  IL_000c:  stfld      int32 ClassAndStruct.Program/SomeStructVal::x  IL_0011:  ldloc.0  IL_0012:  box        ClassAndStruct.Program/SomeStructVal  IL_0017:  stloc.1  IL_0018:  ldloc.1  IL_0019:  unbox.any  ClassAndStruct.Program/SomeStructVal  IL_001e:  stloc.2  IL_001f:  ldloca.s   v2  IL_0021:  ldc.i4.s   11  IL_0023:  stfld      int32 ClassAndStruct.Program/SomeStructVal::x  IL_0028:  ldloc.1  IL_0029:  unbox.any  ClassAndStruct.Program/SomeStructVal  IL_002e:  stloc.3  IL_002f:  ldstr      "v2.x="  IL_0034:  ldloca.s   v2  IL_0036:  ldflda     int32 ClassAndStruct.Program/SomeStructVal::x  IL_003b:  call       instance string [mscorlib]System.Int32::ToString()  IL_0040:  call       string [mscorlib]System.String::Concat(string,                                                              string)  IL_0045:  call       void [mscorlib]System.Console::WriteLine(string)  IL_004a:  nop  IL_004b:  ldstr      "o.x="  IL_0050:  ldloca.s   v3  IL_0052:  ldflda     int32 ClassAndStruct.Program/SomeStructVal::x  IL_0057:  call       instance string [mscorlib]System.Int32::ToString()  IL_005c:  call       string [mscorlib]System.String::Concat(string,                                                              string)  IL_0061:  call       void [mscorlib]System.Console::WriteLine(string)  IL_0066:  nop  IL_0067:  ret} // end of method Program::Unbox

我們可以看到在  IL_0012:  box    IL_0019:  unbox.any    IL_0029:  unbox.any 三個地方進行了裝箱和拆箱的操作。

將v賦值給o時執行了裝箱操作,再將o轉換成v2時執行了拆箱操作。但對v2.x進行賦值後,並沒有影響o的值(o轉換成為v3輸出)。

綜上,我們可以看到struct和class兩者有很大的差別,而這差別根本是因為值類型和參考型別的差別。

下面總結了struct使用的一些條件,僅供參考

1.該類型作為基本類型,且其成員都是基本的類型,沒有參考型別。並且該類型不會繼承其他類型,也不會被其他類型繼承。
2.執行個體佔用的位元組數很小(一般是小於等於16位元組)
3.如果執行個體的位元組數大於16,但不會作為參數在方法中傳遞,或者從方法中返回時。

轉載請註明出處

http://blog.csdn.net/xxdddail/article/details/36862275

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.