简体   繁体   中英

C# - Method inside generic class with additional constraints to T

I have a generic class Foo<T> where T: SomeBaseType .

And in the specific case where T is SpecificDerivedType , I want my class to have an additional method.

Something like:

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

How can I achieve this?

Make an extension method for Foo<T> :

public static void SpecialMethod<T>(this Foo<T> foo)
    where T : SpecificDerivedType
{
}

How can I achieve this?

You can't. Create a specialized Foo .

class SpecialFoo<T> : Foo<T> where T: SpecificDerivedType
{
    void SpecialMethod()
    {
        //...code...
    }
}

Other suggest an extension method , which is obviously not the same as what you ask. It might be a workaround though.

There's nothing quite like that, but you could add an extension method on Foo<T> with a more specific constraint than T normally has. Here's a complete example:

using System;

class SomeBaseType {}
class SomeDerivedType : SomeBaseType {}

static class FooExtensions
{
    public static void Extra<T>(this Foo<T> foo)
        where T : SomeDerivedType
    {
        Console.WriteLine("You have extra functionality!");
    }
}

class Foo<T> where T : SomeBaseType
{
}

class Program
{
    static void Main(string[] args)        
    {
        Foo<SomeBaseType> foo1 = new Foo<SomeBaseType>();
        Foo<SomeDerivedType> foo2 = new Foo<SomeDerivedType>();

        // Doesn't compile: the constraint isn't met
        // foo1.Extra();

        // Does compile
        foo2.Extra();
    }
}

That allows you to call the method on an existing instance rather than having to create a more specialized instance. On the other hand, it relies on the extension method having enough access to do whatever it needs to in Foo<T> . You may need to have an unconstrained internal method in Foo<T> for FooExtensions.Extra to call.

You can create an extension method that will look like this:

public static void SpecificMethod<T>(this Generic<T> instance) 
    where T : SpecificDerivedType

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