Ale*_*x F 8 c# generics constraints
我想编写应该使用的泛型类byte和ushort类型.我应该为这门课使用什么约束?如何检测MaxValue此类内部的属性?
class MyClass<T> // where T: ???
{
void Foo()
{
int maxValue = T.MaxValue; // how can I do this?
}
}
Run Code Online (Sandbox Code Playgroud)
如果类是使用意外类型创建的,它不包含MaxValue属性,我不在乎 - 例如,我可以在运行时抛出异常.
一种方法是利用新dynamic关键字:
void Main()
{
Test(10);
Test(10.234);
Test((Byte)42);
Test(true);
}
public void Test<T>(T value)
where T : struct
{
T maxValue = MaxValue((dynamic)value);
maxValue.Dump();
}
public int MaxValue(int dummy)
{
return int.MaxValue;
}
public double MaxValue(double dummy)
{
return double.MaxValue;
}
public byte MaxValue(byte dummy)
{
return byte.MaxValue;
}
public object MaxValue(object dummy)
{
// This method will catch all types that has no specific method
throw new NotSupportedException(dummy.GetType().Name);
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用反射来获取MaxValue字段:
void Main()
{
Test(10);
Test(10.234);
Test((Byte)42);
Test(true);
}
public void Test<T>(T value)
where T : struct
{
FieldInfo maxValueField = typeof(T).GetField("MaxValue", BindingFlags.Public
| BindingFlags.Static);
if (maxValueField == null)
throw new NotSupportedException(typeof(T).Name);
T maxValue = (T)maxValueField.GetValue(null);
maxValue.Dump();
}
Run Code Online (Sandbox Code Playgroud)
您可以通过LINQPad测试这两个程序.
尝试这样的事情
public T GetMaxValue()
{
object maxValue = default(T);
TypeCode typeCode = Type.GetTypeCode(typeof(T));
switch (typeCode)
{
case TypeCode.Byte:
maxValue = byte.MaxValue;
break;
case TypeCode.Char:
maxValue = char.MaxValue;
break;
case TypeCode.DateTime:
maxValue = DateTime.MaxValue;
break;
case TypeCode.Decimal:
maxValue = decimal.MaxValue;
break;
case TypeCode.Double:
maxValue = decimal.MaxValue;
break;
case TypeCode.Int16:
maxValue = short.MaxValue;
break;
case TypeCode.Int32:
maxValue = int.MaxValue;
break;
case TypeCode.Int64:
maxValue = long.MaxValue;
break;
case TypeCode.SByte:
maxValue = sbyte.MaxValue;
break;
case TypeCode.Single:
maxValue = float.MaxValue;
break;
case TypeCode.UInt16:
maxValue = ushort.MaxValue;
break;
case TypeCode.UInt32:
maxValue = uint.MaxValue;
break;
case TypeCode.UInt64:
maxValue = ulong.MaxValue;
break;
default:
maxValue = default(T);//set default value
break;
}
return (T)maxValue;
}
Run Code Online (Sandbox Code Playgroud)