此代码会生成一个编译器错误,指出该成员已使用相同的参数类型进行定义。
private T GetProperty<T>(Func<Settings, T> GetFunc) where T:class
{
try
{
return GetFunc(Properties.Settings.Default);
}
catch (Exception exception)
{
SettingReadException(this,exception);
return null;
}
}
private TNullable? GetProperty<TNullable>(Func<Settings, TNullable> GetFunc) where TNullable : struct
{
try
{
return GetFunc(Properties.Settings.Default);
}
catch (Exception ex)
{
SettingReadException(this, ex);
return new Nullable<TNullable>();
}
}
有干净的解决办法吗?
最佳答案
通用类型约束不能用于重载解析,但您实际上不需要为此使用重载方法。只需使用 default
而不是 null
:
private T GetProperty<T>(Func<Settings, T> GetFunc)
{
try
{
return GetFunc(Properties.Settings.Default);
}
catch (Exception exception)
{
SettingReadException(this,exception);
return default(T);
}
}
哦,我已经逐字复制了您的代码,但是请不要像这样吞下一般的Exception
。捕获您实际预期可能抛出的特定异常。您不希望此代码无意中吞掉 OutOfMemoryException
或 BadImageFormatException
实例。
关于c# - 不明确的通用限制 T :class vs T:struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718442/