我正在使用以下方法。
public static Generic Get<Generic>(this object self)
{
try { return (Generic)self; }
catch (Exception) { return default(Generic); }
}
一项新要求说,如果Int64为null,则需要将其映射到-13。我试图通过返回上述修复值(如果类型为Int64)来实现这一点。
public static Generic Get<Generic>(this object self)
{
if (self == null && typeof (Generic) == typeof (long))
return -13;
try { return (Generic)self; }
catch (Exception) { return default(Generic); }
}
但是,编译器与我不同意,因为它担心当Generic类型与所述值不兼容时我将返回-13。我该如何解决?
我尝试使用Google搜索自定义默认值,但得到了nada。
您可以object
先将其装箱:
return (Generic)(object)-13;
然后,您将获得一串由两个转换组成的链,这些转换在编译时是可以接受的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句