繁体   English   中英

可空 <T> 对于c#中的泛型方法?

[英]Nullable<T> for generic method in c#?

如何编写可以将Nullable对象用作扩展方法的泛型方法。 我想向父元素添加一个XElement,但前提是要使用的值不为null。

例如

public static XElement AddOptionalElement<T>(this XElement parentElement, string childname, T childValue){
...
code to check if value is null
add element to parent here if not null
...
}

如果我使这个AddOptionalElement<T?>(...)然后我得到编译器错误。 如果我使这个AddOptionalElement<Nullable<T>>(...)然后我得到编译器错误。

有没有办法可以实现这个目标?

我知道我可以调用这个方法:

parent.AddOptionalElement<MyType?>(...)

但这是唯一的方法吗?

public static XElement AddOptionalElement<T>(
    this XElement parentElement, string childname, T? childValue)
    where T : struct
{
    // ...
}

您需要将T约束为struct - 否则它不能为空。

public static XElement AddOptionalElement<T>(this XElement parentElement, 
                                             string childname, 
                                             T? childValue) where T: struct { ... }

尝试
AddOptionalElement<T>(T? param) where T: struct { ... }

Nullable类型具有约束where T : struct, new()因此您的方法应该包含struct约束以使Nullable<T>正常工作。 生成的方法应如下所示:

public static XElement AddOptionalElement<T>(this XElement parentElement, string childname, T? childValue) where T : struct
    {
      // TODO: your implementation here
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM