对于c#中的泛型方法,可以为<t> </t>

时间:2010-12-20 10:54:05

标签: c# generics nullable

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

e.g。

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?>(...)

但这是唯一的方法吗?

4 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:4)

您需要将T限制为struct - 否则无法为空。

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

The 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
    }
相关问题