【问题标题】:What is the equivalent of C++ Template Inheritance in C#?C# 中的 C++ 模板继承等价物是什么?
【发布时间】:2016-03-17 06:46:55
【问题描述】:

我知道这在 C# 中是不可能的,因为泛型不是模板,它们的实现方式不同(在运行时处理而不是在编译期间处理):

public class Foo<T> : T
{

}

问题仍然存在。是否有等效或替代方法来实现这一目标?

在我的例子中,我想要继承三个不同的父类,我们称它们为 A、B、C:

public class A {}

public class B {}

public class C {}

然后我有 Foo 类,然后还有更多从 Foo 继承,但它们中的每一个只需要 A、B、C 之一:

public class X : Foo<A> {} 

public class Y : Foo<B> {}

public class Z : Foo<C> {}

所以类 X 需要 Foo 中的所有功能以及 A 中的所有功能,Y 来自 Foo 和 B 等等......

如何在 C# 中做到这一点?

【问题讨论】:

  • 那么答案中没有 cmets 吗?我认为这是一个有趣的话题

标签: c# oop generics inheritance design-patterns


【解决方案1】:

我想你不能修改 A、B 和 C 类(否则你可以从 Foo 继承所有它们),因此这是我的想法: 我将“Foo”定义为一个接口(我称之为“IFoo”):

public interface IFoo {}

并将其所有方法实现为扩展方法:

public static class IFooExtension
{
    public static void Method1(this IFoo f) {
        // do whatever here;
    } 
}

然后我将进一步声明如下:

public class X : A, IFoo {}
public class Y : B, IFoo {}
public class Z : C, IFoo {}

唯一的问题(如果是问题的话)是您可以实现任何您想要的方法,但没有属性。

【讨论】:

    【解决方案2】:

    如果class X: Foo&lt;A&gt; { } 需要FooA 的所有功能,那么只需将A 公开为属性即可:

    public class Foo<T> where T : new()
    {
        public T Bar { get; } = new T();
        public void FooMethod() => Console.WriteLine("Foo method");
    }
    
    public class A
    {
        public void AMethod() => Console.WriteLine("A method");
    }
    
    public class X : Foo<A>
    {
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var x = new X();
            x.FooMethod();
            x.Bar.AMethod(); // access via property
        }
    }
    

    【讨论】:

    • 可能这就是他已经在做的事情(否则为什么要通用定义?)。无论如何它都会起作用,它只是“与 C++ 模板继承不同”(派生类看起来不像直接从多个父类继承)
    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    相关资源
    最近更新 更多