模糊的通用限制T:class vs T:struct

此代码生成编译器错误,该成员已使用相同的参数类型定义。

private T GetProperty(Func GetFunc) where T:class { try { return GetFunc(Properties.Settings.Default); } catch (Exception exception) { SettingReadException(this,exception); return null; } } private TNullable? GetProperty(Func GetFunc) where TNullable : struct { try { return GetFunc(Properties.Settings.Default); } catch (Exception ex) { SettingReadException(this, ex); return new Nullable(); } } 

有干净的工作吗?

通用类型约束不能用于重载解析,但实际上您不需要重载方法。 只需使用default而不是null

 private T GetProperty(Func GetFunc) { try { return GetFunc(Properties.Settings.Default); } catch (Exception exception) { SettingReadException(this,exception); return default(T); } } 

哦,我已经逐字复制了你的代码,但不要像这样吞下一般的Exception 。 捕获您实际可能会抛出的特定exception。 您不希望此代码无意中吞噬OutOfMemoryExceptionBadImageFormatException实例。