比方说你有一个Type叫做primitiveType用primitiveType.IsPrimitive == true,你怎么能最succintly(不使用第三方库)创建的这个实例与非零值(例如,值= 1)?
也就是说,该功能可能如下所示:
public static object CreateNonZero(Type primitiveType)
{
if (!primitiveType.IsPrimitive)
{ throw new ArgumentException("type must be primitive"); }
// TODO
}
Run Code Online (Sandbox Code Playgroud)
也就是说,它应该适用于所有原始值类型,例如bool,byte,sbyte,short,ushort,int,uint,long,ulong,float,double,IntPtr,UIntPtr,char等.
Convert.ChangeType(1, primitiveType)
Run Code Online (Sandbox Code Playgroud)
请注意,如果您希望返回类型与实际类型匹配而不是object,则执行通用版本相对容易:
public static T CreateNonZero<T>()
{
return (T)Convert.ChangeType(1, typeof(T));
}
Run Code Online (Sandbox Code Playgroud)
如果你想处理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);
}
Run Code Online (Sandbox Code Playgroud)