模糊的通用限制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。 您不希望此代码无意中吞噬OutOfMemoryException
或BadImageFormatException
实例。
上述就是C#学习教程:模糊的通用限制T:class vs T:struct分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/953429.html