我写了这个简单的实用函数:
public static T isNull<T>(T? v, T d)
{
return v == null ? d : v.Value;
}
目的是避免烦人的任务,例如检查成员是否为空,这在读取 linq 记录集时很常见。问题是它抛出了这个错误:
The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable< T>'
错误似乎是合法的,无论如何我希望我能做这样的事情:
int? myField = record.myField;
int myValue = isNull(myField, 0);
代替:
int? myField = record.myField;
int myValue = myField == null ? 0 : myField.Value;
我觉得我缺少一些 c# 基础知识。是否存在完成我的任务的方法?
最佳答案
Generic constraints 可用于泛型函数以限制允许用于某些子集的类型,这为您如何在方法或类中使用这些类型开辟了可能性。
在这种情况下,您可以对 T
应用约束,将其限制为 struct
以解决特定的编译器错误。
public static T IsNull<T>(T? v, T d) where T : struct
{
return v == null ? d : v.Value;
}
但是,另一个答案确实正确地指出您可以选择在这种特定 情况下使用空合并运算符??
。
关于c# - 通用类型函数 : return a non-nullable value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696120/