Kri*_*per 4 c# generics types casting nullable
我有一个方法包装一些经常返回的外部API调用null
.当它发生时,我想返回一个default
值.该方法看起来像这样
public static T GetValue<T>(int input)
{
object value = ExternalGetValue(input);
return value != null ? (T)value : default(T)
}
Run Code Online (Sandbox Code Playgroud)
问题是(T)value
可能抛出无效的强制转换异常.所以我想我会改成它
var value = ExternalGetValue(input) as Nullable<T>;
Run Code Online (Sandbox Code Playgroud)
但这需要where T : struct
,我也希望允许引用类型.
然后我尝试添加一个可以处理两者的重载.
public static T GetValue<T>(int input) where T : struct { ... }
public static T GetValue<T>(int input) where T : class { ... }
Run Code Online (Sandbox Code Playgroud)
但我发现你不能根据约束重载.
我意识到我可以有两个不同名称的方法,一个用于可空类型,一个用于不可用类型,但我宁愿不这样做.
有没有一种好方法可以检查我是否可以在T
不使用的情况下进行投射as
?或者我可以使用as
并拥有适用于所有类型的单一方法吗?
你可以使用is
:
return value is T ? (T)value : default(T);
Run Code Online (Sandbox Code Playgroud)
(注意,如果为null ,value is T
则返回.)false
value
归档时间: |
|
查看次数: |
766 次 |
最近记录: |