如何在c#中获得泛型数字类型的最大值和最小值?



我有一个称为TValue的泛型类型。我想这样做:


public TValue Number {get;set;}
public TValue GetMaxNumber()
{
switch (Number)
{
case int @int:
if (@int == default(int))
{
return int.MaxValue;
}
case long @long:
//get max value of long
case short @short:
//get max value of short
case float @float:
//get max value of float
case double @double:
//get max value of double
case decimal @decimal:
//get max value of decimal
default:
throw new InvalidOperationException($"Unsupported type {Number.GetType()}");
}
}

我希望GetMaxNumber方法返回该数字类型的最大可能值。如果不是数字类型,则抛出异常。

我在这里遇到的主要问题是,我不明白如何在使用int的属性(如MaxValue)时将int类型转换回原始泛型类型。

我如何使它工作?

如果性能不是一个大问题,你想避免有一个大的切换,你可以用反射来做(并尝试/catch)

public TValue GetMaxNumber()
{
try
{
return (TValue)typeof(TValue).GetField("MaxValue").GetValue(null);
}
catch
{
throw new InvalidOperationException($"Unsupported type {typeof(TValue)}");
}
}

可以这样转换:

return (TValue)(object)int.MaxValue;

Boxing允许打开相关的泛型类型参数。

未测试,但可能转换。ChangeType:

var conversionType = typeof(TValue);
return (TValue)Convert.ChangeType(int.MaxValue, conversionType);

相关内容

最新更新