gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:51:44 24 4
gpt4 key购买 nike

假设您有一个名为 primitiveTypeTypeprimitiveType.IsPrimitive == true,您如何最简洁地(不使用第三个-party library)创建一个非零值的实例(例如值= 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);
}

关于c# - 在 C# 中给定 Type 创建任何数字/原始值类型的非零实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23808396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com