我有一些通用的方法
T SomeMethod(Func<T> func){
T result = func();
if (result != null)
{ //.....}
}
如果 T
是类,它会很好地工作。但是T
是struct怎么办?如果 T
是 struct
,我如何检查 result == default(T)
?
附言我不想使用约束 where T: class
或 Nullable
类型。
最佳答案
执行此操作的更惯用的方法是遵循 int.TryParse
之类的方法。
public delegate bool TryFunction<T>(out T result);
T SomeMethod(TryFunction<T> func)
{
T value;
if(func(out value))
{
}
}
关于c# - 如果 struct 不可为空,则在 C# 中检查 struct 是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7894719/