繁体   English   中英

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

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

我有一个泛型类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...
    }
}

我怎样才能做到这一点?

Foo<T>一个扩展方法

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

我怎样才能做到这一点?

你不能。 创建一个专门的Foo

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

其他建议使用扩展方法 ,这显然与您提出的方法不同。 这可能是一种解决方法。

没有什么比这更像了,但你可以Foo<T>上添加一个扩展方法 ,其具有比T通常具有的更具体的约束。 这是一个完整的例子:

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();
    }
}

这允许您在现有实例上调用该方法,而不必创建更专业的实例。 另一方面,它依赖于具有足够访问权限的扩展方法来执行Foo<T>所需的任何操作。 你可能需要在Foo<T>有一个不受约束的internal方法来调用FooExtensions.Extra

您可以创建一个如下所示的扩展方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM