假设您有一个名为Type with primitiveType.IsPrimitive == true的primitiveType,那么如何最简洁地(不使用第三方库)创建一个非零值的实例(例如,value = 1)?
也就是说,这个函数看起来可能是:
public static object CreateNonZero(Type primitiveType)
{
if (!primitiveType.IsPrimitive)
{ throw new ArgumentException("type must be primitive"); }
// TODO
}也就是说,它应该适用于所有的原始值类型,如bool、字节、字节、短、ushort、int、uint、long、ulong、float、double、IntPtr、UIntPtr、char等。
发布于 2014-05-22 13:33:41
Convert.ChangeType(1, primitiveType)注意,如果您希望返回类型与实际类型匹配,而不是成为object,那么执行泛型版本相对容易:
public static T CreateNonZero<T>()
{
return (T)Convert.ChangeType(1, typeof(T));
}如果您想处理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);
}https://stackoverflow.com/questions/23808396
复制相似问题