【发布时间】:2011-08-19 05:12:39
【问题描述】:
可能的重复:
Why cannot C# generics derive from one of the generic type parameters like they can in C++ templates?
In C# 4.0, is it possible to derive a class from a generic type parameter?
我正在尝试创建一个从其泛型类型继承的泛型类(在 1.Attempt 中)。看起来是不可能的。但在其他尝试中,我必须投射物体。有什么设计方案可以解决这个问题吗?
// #1 Attempt
public interface IFoo { }
public class Generic<T> : T { }
public void play ()
{
IFoo genfoo = new Generic<IFoo> ();
}
.
// #2 Attempt. Castable solution
public interface IAnything { }
public interface IFoo2 : IAnything { }
public class Generic2<T> : IAnything { }
public void play2 ()
{
IFoo2 genFoo = (IFoo2) new Generic2<IFoo2> ();
}
【问题讨论】:
-
我看不出这是可能的,不管有没有强制转换。你想做什么?根据您的情况,您可能正在寻找诸如 Castle.DynamicProxy 之类的东西,或者可能是一个模拟框架...
-
拥有一个必须从泛型类型继承的泛型类有什么意义?它打败了通用目标。
-
你是什么意思,继承还是实现?你说“继承”,但举一个接口作为例子。
-
另外,这里有很多很好的信息:stackoverflow.com/questions/1849107/…
-
另外,昨天也有人问过这个问题:stackoverflow.com/questions/5890516/…