给定C#中的Type,创建任意数值/原始值类型的非零实例

nie*_*ras 1 c# reflection

比方说你有一个Type叫做primitiveTypeprimitiveType.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等.

Ben*_*son 9

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)

如果你想处理IntPtrUIntPtr,我不知道有什么更优雅的方式,而不是明确检查的类型

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)