2015-05-12 29 views
1

我想編寫計算值類型大小的方法。但我不能給值類型(int,double,float)作爲方法參數。計算值類型(int,float,string)使用通用方法的C#中的大小

/* 
    *When i call this method with SizeOf<int>() and 
    *then it returns 4 bytes as result. 
    */ 
    public static int SizeOf<T>() where T : struct 
    { 
     return Marshal.SizeOf(default(T)); 
    } 

    /* 
    *When i call this method with TypeOf<int>() and 
    *then it returns System.Int32 as result. 
    */ 
    public static System.Type TypeOf<T>() 
    { 
     return typeof(T); 
    } 

我不想那樣。我想寫下這個方法如下。

/* 
    *When i call this method with GetSize(int) and 
    *then it returns error like "Invalid expression term 'int'". 
    */ 
    public static int GetSize(System.Type type) 
    { 
     return Marshal.SizeOf(type); 
    } 

那麼我如何傳遞值類型(int,double,float,char ..)到方法參數來計算它的大小一般。

+0

[如何獲取通用列表中的字節大小的類型?]可能的重複(http://stackoverflow.com/questions/7255951/how-to-get-byte-size-of-type-in​​-generic-列表) – Avantol13

回答

1

你得到一個錯誤的GetSize(int)的原因是,int是不是值。您需要使用typeof,如下所示:GetSize(typeof(int)),或者如果您有實例,則:GetSize(myInt.GetType())

+0

問題解決了。謝謝阿米特。 –

1

現有的代碼只是工作:

public static int GetSize(System.Type type) 
{ 
    return Marshal.SizeOf(type); 
} 

不知道哪裏的錯誤是從您發佈而不是從這個未來。如果你願意,你可以使這個通用:

public static int GetSize<T>() 
{ 
    return Marshal.SizeOf(typeof(T)); 
} 
+0

它似乎是OPs錯誤消息的奧祕是由於調用'GetSize(int)'而不是'GetSize(typeof(int))' – Alex

+0

他發佈了代碼,這將是顯而易見的。不錯的猜測。 – usr

相關問題