简体   繁体   中英

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. I want to add an XElement to a parent element, but only if the value to be used is not 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. If I make this AddOptionalElement<Nullable<T>>(...) then I get compiler errors.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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