How can I write a generic method that can take a Nullable object to use as an extension method. I want to add an开发者_StackOverflow中文版 XElement to a parent element, but only if the value to be used is not 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
...
}
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 { ... }
try
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
}
精彩评论