Dal*_*ale 2 c# generics nullable
我有这个代码:
//Return null if the extension doesn't have the value, returns the value if it does.
private T? getValue<T>(IEnumerable<Extension> extension, string attributeName)
{
IEnumerable<Extension> ext = extension.Where(e => e.attributeName == attributeName);
if (ext.Count() > 0)
{
return (T)ext.First().Attribute;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我称之为:
//This works:
retVal.byteValue= getValueFromExtension<byte>(u, "ByteToGet") ?? 0;
//This doesn't work:
getValueFromExtension<string>(u, "Text") ?? "";
Run Code Online (Sandbox Code Playgroud)
我得到编译错误:"错误消息:"无法转换类型'字符串?' 'string'"
如何在不创建新方法的情况下有效地完成上述代码中的想法?
我觉得我正在检查它是否为空?运算符,因此,如果字符串为null,则始终将其设置为空字符串.它是如何处理我对字节和int的期望,为什么不为字符串?
FYI,上面的byteValue,是字节类型,而不是字节?
null
如果它是一个引用类型,0
并且它是一个数字或类似的值类型,它似乎你想要.您只需使用default
关键字即可获得此类值T
.此外,您可能希望将this
关键字添加到第一个参数,以便可以将其用作扩展方法.
private T getValue<T>(this IEnumerable<Extension> extension, string attributeName)
{
Extension ext = extension.SingleOrDefault(e => e.attributeName == attributeName);
if (ext != null)
return (T)ext.Attribute;
else
return default(T);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4649 次 |
最近记录: |