C# - 泛型类中的方法,对T有附加约束

Dan*_*ler 4 c# oop generics

我有一个通用类Foo<T> where T: SomeBaseType.

而在特定的情况下,TSpecificDerivedType的,我希望我的班有一个额外的方法.

就像是:

class Foo<T> where T: SomeBaseType
{
    //.... lots of regular methods taking T, outputting T, etc.

    //in pseudo code
    void SpecialMethod() visible if T: SpecificDerivedType
    {
        //...code...
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Ser*_*rvy 7

做一个扩展方法Foo<T>:

public static void SpecialMethod<T>(this Foo<T> foo)
    where T : SpecificDerivedType
{
}
Run Code Online (Sandbox Code Playgroud)