我想編寫計算值類型大小的方法。但我不能給值類型(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 ..)到方法參數來計算它的大小一般。
[如何獲取通用列表中的字節大小的類型?]可能的重複(http://stackoverflow.com/questions/7255951/how-to-get-byte-size-of-type-in-generic-列表) – Avantol13