C#中的泛型方法可以为Nullable <T>?

Blu*_*ppy 10 c# generics nullable

如何编写可以将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
...
}
Run Code Online (Sandbox Code Playgroud)

如果我这样做,AddOptionalElement<T?>(...)那么我会遇到编译错误.如果我这样做,AddOptionalElement<Nullable<T>>(...)那么我会遇到编译错误.

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

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

parent.AddOptionalElement<MyType?>(...)
Run Code Online (Sandbox Code Playgroud)

但这是唯一的方法吗?

Luk*_*keH 12

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