如何檢查結(jié)構(gòu)消耗的字節(jié)數(shù)?如果我創(chuàng)建一個相對較大的結(jié)構(gòu),我如何計算它在內(nèi)存中占用的字節(jié)數(shù)?我們可以手動完成,但如果結(jié)構(gòu)足夠大,那么我們該怎么做呢?是否有一些代碼塊或應(yīng)用程序?
3 回答

largeQ
TA貢獻2039條經(jīng)驗 獲得超8個贊
您可以使用sizeof
運算符或SizeOf
函數(shù)。
這些選項之間存在一些差異,請參閱參考鏈接以獲取更多信息。
無論如何,使用該函數(shù)的一個好方法是使用這樣的泛型方法或擴展方法:
static class Test{ static void Main() { //This will return the memory usage size for type Int32: int size = SizeOf<Int32>(); //This will return the memory usage size of the variable 'size': //Both lines are basically equal, the first one makes use of ex. methods size = size.GetSize(); size = GetSize(size); } public static int SizeOf<T>() { return System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); } public static int GetSize(this object obj) { return System.Runtime.InteropServices.Marshal.SizeOf(obj); }}

一只萌萌小番薯
TA貢獻1795條經(jīng)驗 獲得超7個贊
您可以將sizeof()關(guān)鍵字用于不包含任何字段或?qū)傩宰鳛橐妙愋偷挠脩舳x結(jié)構(gòu),也可以使用Marshal.SizeOf(Type)或Marshal.SizeOf(object)獲取具有順序或顯式布局的類型或結(jié)構(gòu)的非托管大小。
- 3 回答
- 0 關(guān)注
- 427 瀏覽
添加回答
舉報
0/150
提交
取消