繁体   English   中英

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

[英]Create a non-zero instance of any number/primitive value type given a Type in C#

假设您有一个称为primitiveTypeType为nativeType.IsPrimitive primitiveType.IsPrimitive == true ,如何最简洁地(不使用第三方库)创建一个具有非零值(例如value = 1)的实例?

也就是说,该函数可能如下所示:

public static object CreateNonZero(Type primitiveType)
{
    if (!primitiveType.IsPrimitive)
    { throw new ArgumentException("type must be primitive"); }

    // TODO
}

也就是说,它应该适用于所有原始值类型,例如bool,byte,sbyte,short,ushort,int,uint,long,ulong,float,double,IntPtr,UIntPtr,char等。

Convert.ChangeType(1, primitiveType)

请注意,如果您想让返回类型与您的实际类型相匹配而不是成为object ,则进行通用版本相对容易:

public static T CreateNonZero<T>()
{
    return (T)Convert.ChangeType(1, typeof(T));
}

如果您想处理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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM