简体   繁体   English

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

[英]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)? 假设您有一个称为primitiveTypeType为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 如果您想处理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.

相关问题 为什么 C# 允许在浮点类型中将非零数除以零? - Why does C# allow dividing a non-zero number by zero in floating-point type? 包含原始值类型的结构是否是C#中的零成本抽象? - Is a struct wrapping a primitive value type a zero cost abstraction in C#? C# - 获取数组最后一个非零数的索引 - C# - Get the Index of the last non-zero number of an array 检查 C# BitArray 非零值的最快方法 - Fastest way to check C# BitArray for non-zero value C#正则表达式拆分为非零数字,后跟任意数字零 - C# regex split for A non-zero digit followed by an arbitrary number of zero 值类型和原始类型,以及非原始类型和引用类型有什么区别吗? 如果是,那么彼此之间有何不同 - Is there any difference Value Type and Primitive Type, and Non Primitive Type and Reference Type. If yes then how all are different from each other linq c# 无法创建“”类型的常量值。 在此上下文中仅支持原始类型或枚举类型 - linq c# Unable to create a constant value of type ''. Only primitive types or enumeration types are supported in this context C#如何从组合框中的类型列表中的给定反射类型创建实例 - C# How to create an instance from a given reflection Type from a list of Type in a Combo-Box C# - Linq:无法创建类型的常量值在此上下文中仅支持基本类型或枚举类型。 - C# - Linq : Unable to create a constant value of type Only primitive types or enumeration types are supported in this context. C#:基于整数Enu​​m值创建类型的实例 - C#: Create instance of a type based on an integral Enum value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM