使用通用方法计算C#中的值类型(int、float、string)大小
我想写一个计算值类型大小的方法。但我不能将值类型(int、double、float)作为方法参数使用通用方法计算C#中的值类型(int、float、string)大小,c#,generics,types,.net-4.0,value-type,C#,Generics,Types,.net 4.0,Value Type,我想写一个计算值类型大小的方法。但我不能将值类型(int、double、float)作为方法参数 /* *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
/*
*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);
}
因此,我如何将值类型(int、double、float、char..)传递给方法参数,以计算其大小作为泛型。您现有的代码只起作用:
public static int GetSize(System.Type type)
{
return Marshal.SizeOf(type);
}
不确定错误是从哪里来的,但不是从这个。如果需要,您可以将其设置为通用:
public static int GetSize<T>()
{
return Marshal.SizeOf(typeof(T));
}
publicstaticintgetsize()
{
返回Marshal.SizeOf(typeof(T));
}
获取GetSize(int)
错误的原因是int
不是一个值。您需要像这样使用typeof
:GetSize(typeof(int))
,或者如果您有一个实例:GetSize(myInt.GetType())
它可能重复出现关于OPs错误消息的秘密是由于调用GetSize(int)
而不是GetSize(typeof(int))
他是否发布了代码?这是显而易见的。猜对了。
public static int GetSize<T>()
{
return Marshal.SizeOf(typeof(T));
}