I want to write method which calculate value types size. But i can't give value types (int, double, float) as method parameter.
我想编写计算值类型大小的方法。但我不能将值类型(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(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);
}
I don't want it that way.I want to write this method as below.
我不想那样。我想写下这个方法。
/*
*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);
}
So how can i pass value types (int, double, float, char ..) to method parameters to calculate it's size as generic.
那么我如何将值类型(int,double,float,char ..)传递给方法参数来计算它的大小为通用。
2 个解决方案
#1
The reason you get an error for GetSize(int)
is that int
is not a value. You need to use typeof
like so: GetSize(typeof(int))
, or if you have an instance then: GetSize(myInt.GetType())
.
GetSize(int)出错的原因是int不是值。你需要像这样使用typeof:GetSize(typeof(int)),或者你有一个实例:GetSize(myInt.GetType())。
#2
Your existing code just works:
您现有的代码正常工作:
public static int GetSize(System.Type type)
{
return Marshal.SizeOf(type);
}
Not sure where that error is coming from that you posted but not from this. If you want to you can make this generic:
不确定该错误来自您发布的错误,但不是来自此错误。如果你愿意,你可以使这个通用:
public static int GetSize<T>()
{
return Marshal.SizeOf(typeof(T));
}
#1
The reason you get an error for GetSize(int)
is that int
is not a value. You need to use typeof
like so: GetSize(typeof(int))
, or if you have an instance then: GetSize(myInt.GetType())
.
GetSize(int)出错的原因是int不是值。你需要像这样使用typeof:GetSize(typeof(int)),或者你有一个实例:GetSize(myInt.GetType())。
#2
Your existing code just works:
您现有的代码正常工作:
public static int GetSize(System.Type type)
{
return Marshal.SizeOf(type);
}
Not sure where that error is coming from that you posted but not from this. If you want to you can make this generic:
不确定该错误来自您发布的错误,但不是来自此错误。如果你愿意,你可以使这个通用:
public static int GetSize<T>()
{
return Marshal.SizeOf(typeof(T));
}