开发者

Generic generic extension method (sic!)

开发者 https://www.devze.com 2023-04-13 08:33 出处:网络
Is it 开发者_C百科possible to add an extension method to a generic class that is independent of that class\' instance generic type?

Is it 开发者_C百科possible to add an extension method to a generic class that is independent of that class' instance generic type?

I want to write a extension method for handling Nullable values. So far, the method looks like this:

public static object GetVerifiedValue(this Nullable<> obj)
{
    return obj.HasValue ? obj.Value : DBNull.Value;
}

But the compiler doesn't accept the Nullable<> type.

Is there any way I can do this?

Note: I'm using C# 3.0, .NET 3.5.


Just make it a generic method:

public static object GetVerifiedValue<T>(this Nullable<T> obj)
    where T : struct
{
    return obj.HasValue ? obj.Value : DBNull.Value;
}

The calling code can use type inference when calling it:

int? x = 10;
object o = x.GetVerifiedValue();

EDIT: Another option is to use the boxing behaviour of nullable types:

public static object GetVerifiedValue(object obj)
{
    return obj ?? DBNull.Value;
}

Of course that doesn't verify that you're trying to pass in an expression of a nullable value type...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号