[英]Create a non-zero instance of any number/primitive value type given a Type in C#
Lets say you have a Type
called primitiveType
with primitiveType.IsPrimitive == true
, how can you most succintly (without using a third-party library) create an instance of this with a non-zero value (eg value = 1)? 假设您有一个称为primitiveType
的Type
为nativeType.IsPrimitive primitiveType.IsPrimitive == true
,如何最简洁地(不使用第三方库)创建一个具有非零值(例如value = 1)的实例?
That is, the function could look like: 也就是说,该函数可能如下所示:
public static object CreateNonZero(Type primitiveType)
{
if (!primitiveType.IsPrimitive)
{ throw new ArgumentException("type must be primitive"); }
// TODO
}
That is, it should work for all primitive value types eg bool, byte, sbyte, short, ushort, int, uint, long, ulong, float, double, IntPtr, UIntPtr, char etc. 也就是说,它应该适用于所有原始值类型,例如bool,byte,sbyte,short,ushort,int,uint,long,ulong,float,double,IntPtr,UIntPtr,char等。
Convert.ChangeType(1, primitiveType)
Note if you wanted to have the return type match your actual type rather than be object
, it's relatively easy to do a generic version: 请注意,如果您想让返回类型与您的实际类型相匹配而不是成为object
,则进行通用版本相对容易:
public static T CreateNonZero<T>()
{
return (T)Convert.ChangeType(1, typeof(T));
}
If you want to handle IntPtr
and UIntPtr
, I don't know of any more elegant way than to check the type explicitly 如果您想处理IntPtr
和UIntPtr
,我不知道有什么比显式检查类型更优雅的方法了
public static object CreateNonZero(Type type)
{
if(type == typeof(IntPtr))
return new IntPtr(1);
if(type == typeof(UIntPtr))
return new UIntPtr(1);
return Convert.ChangeType(1, type);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.