代码之家  ›  专栏  ›  技术社区  ›  Daniel Möller

C#-泛型类内的方法,对T有额外的约束

  •  4
  • Daniel Möller  · 技术社区  · 6 年前

    我有一门普通课 Foo<T> where T: SomeBaseType .

    在具体的情况下 T SpecificDerivedType ,我希望我的类有一个额外的方法。

    比如:

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

    我怎样才能做到这一点?

    4 回复  |  直到 6 年前
        1
  •  7
  •   CodeNotFound dotnetstep    6 年前

    做一个 extension method 对于 Foo<T> :

    public static void SpecialMethod<T>(this Foo<T> foo)
        where T : SpecificDerivedType
    {
    }
    
        2
  •  4
  •   CodeNotFound dotnetstep    6 年前

    我怎样才能做到这一点?

    你不能创造一个专门的 Foo .

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

    其他建议 extension method ,这显然与你的要求不同。不过,这可能是一个解决办法。

        3
  •  4
  •   CodeNotFound dotnetstep    6 年前

    没有什么是这样的,但是你 能够 添加一个 extension method 在…上 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();
        }
    }
    

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

        4
  •  2
  •   CodeNotFound dotnetstep    6 年前

    你可以创建一个 extension method 看起来是这样的:

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