Generic generic extension method (sic!)

Is it 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...

链接地址: http://www.djcxy.com/p/96948.html

上一篇: 混合通用方法和扩展方法

下一篇: 泛型通用扩展方法(原文如此!)