简体   繁体   English

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

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

How can I write a generic method that can take a Nullable object to use as an extension method. 如何编写可以将Nullable对象用作扩展方法的泛型方法。 I want to add an XElement to a parent element, but only if the value to be used is not null. 我想向父元素添加一个XElement,但前提是要使用的值不为null。

eg 例如

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
...
}

If I make this AddOptionalElement<T?>(...) then I get compiler errors. 如果我使这个AddOptionalElement<T?>(...)然后我得到编译器错误。 If I make this AddOptionalElement<Nullable<T>>(...) then I get compiler errors. 如果我使这个AddOptionalElement<Nullable<T>>(...)然后我得到编译器错误。

Is there a way I can acheive this? 有没有办法可以实现这个目标?

I know I can make my call to the method: 我知道我可以调用这个方法:

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

but is this the only way? 但这是唯一的方法吗?

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

You need to constrain T to be a struct - otherwise it cannot be nullable. 您需要将T约束为struct - 否则它不能为空。

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

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

The Nullable type has the constraint where T : struct, new() so your method obviuosly should contain the struct constraint to make Nullable<T> working fine. Nullable类型具有约束where T : struct, new()因此您的方法应该包含struct约束以使Nullable<T>正常工作。 The resulting method should look like: 生成的方法应如下所示:

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