我想知道是否有一种返回通用的方法可以返回int或bool或任何其他数据类型。例如:
private static T GetDefaultValue<T>(SettingType s)
{
switch(s)
{
case s.IntValue:
return 0;
case s.BoolValue:
return false;
case s.DateTimeValue:
return DateTime.MinValue;
}
return 0;
}
并被进一步使用:
...
int x = GetDefaultValue<int>(s.IntValue)
...
我知道可以通过使用对象作为返回类型或使用过载来实现这一点,但是如果它也可以与仿制药一起使用。
它可以,但是您必须对编译器进行战斗,您需要通过对象进行施放才能工作
private static T GetDefaultValue<T>(SettingType s)
{
switch(s)
{
case s.IntValue:
return (T)(object)0;
case s.BoolValue:
return (T)(object)false;
case s.DateTimeValue:
return (T)(object)DateTime.MinValue;
}
throw new NotSupportedException("Unsupported type")
}