C+的等价物是什么+;C#中的模板继承?
我理解这在C#中是不可能的,因为泛型不是模板,它们的实现方式不同(在运行时处理而不是在编译期间): 然后我有了Foo类,还有更多继承自Foo的类,但每个类只需要A、B、C中的一个:C+的等价物是什么+;C#中的模板继承?,c#,oop,generics,inheritance,design-patterns,C#,Oop,Generics,Inheritance,Design Patterns,我理解这在C#中是不可能的,因为泛型不是模板,它们的实现方式不同(在运行时处理而不是在编译期间): 然后我有了Foo类,还有更多继承自Foo的类,但每个类只需要A、B、C中的一个: public class X : Foo<A> {} public class Y : Foo<B> {} public class Z : Foo<C> {} 公共类X:Foo{} 公共类Y:Foo{} 公共类Z:Foo{} 所以类X需要Foo中的所有功能,以及Foo和
public class X : Foo<A> {}
public class Y : Foo<B> {}
public class Z : Foo<C> {}
公共类X:Foo{}
公共类Y:Foo{}
公共类Z:Foo{}
所以类X需要Foo中的所有功能,以及Foo和B中A,Y中的所有功能,等等
如何在C#中做到这一点?我想您不能修改A、B和C类(否则您可以从Foo继承所有这些类),因此我的想法是: 我将“Foo”定义为一个接口(我称之为“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 {}
唯一的问题(如果是问题的话)是您可以实现您想要的任何方法,但是没有属性 如果class X:Foo{}
需要Foo
和A
的所有功能,那么只需将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
}
}
public类Foo其中T:new()
{
公共T条{get;}=new T();
public void foodmethod()=>Console.WriteLine(“Foo方法”);
}
公共A类
{
public void AMethod()=>Console.WriteLine(“方法”);
}
公共类别X:富
{
}
班级计划
{
静态void Main(字符串[]参数)
{
var x=新的x();
x、 方法();
x、 Bar.AMethod();//通过属性访问
}
}
这可能是他已经在做的事情(否则为什么要使用通用定义?)。不管怎样,它都是有效的,它与“C++模板继承”不相似(派生类看起来不像是从多个父类直接继承)。我觉得这是一个有趣的话题
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 {}
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
}
}