我有一个名为 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 之类的东西转换回原始泛型类型。
我该如何完成这项工作?
最佳答案
如果性能不是一个大问题,并且您想避免进行大的切换,您可以通过反射(和 try/catch)来实现
public TValue GetMaxNumber()
{
try
{
return (TValue)typeof(TValue).GetField("MaxValue").GetValue(null);
}
catch
{
throw new InvalidOperationException($"Unsupported type {typeof(TValue)}");
}
}
关于c# - 如何在 C# 中获取通用数字类型的最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68654704/