泛型类继承其泛型类型 [英] Generic class that inherits its generic type
问题描述
可能显示的文件:结果
的为什么不能C#泛型从泛型类型参数之一获得像他们可以在C ++模板?
的在C#4.0,是有可能从一个泛型类型参数派生类?
块引用>
我试图创建一个从(在1.Attempt)的泛型类型继承的泛型类。看起来这是不可能的。但在其他尝试,我必须投的对象。任何设计解决这一问题?
//#1尝试
公共接口的IFoo {}
公共类通用< T> :T已{}
公共无效播放()
{
的IFoo genfoo =新的通用<的IFoo> ();
}
//#2尝试。浇注料液
公共接口IAnything {}
公共接口IFoo2:IAnything {}
公共类Generic2< T> :IAnything {}
公共无效play2()后
{
IFoo2 genFoo =(IFoo2)新Generic2< IFoo2> ();
}
解决方案我看不到点你尝试#1中提供的代码。为什么你会继承一个类,然后传递同一类的通用参数。
不过,通用继承支持,但其做不同,请检查此链接,可能会给你一个想法:通用继承
希望这有助于。
Possible Duplicates:
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?I'm trying to create a generic class that inherits from its generic type (in 1.Attempt). Looks like it's impossible. But in other attempt i must cast the object. Any design solution to that problem?
// #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> (); }
解决方案I don't see the point of the code you provided in Attempt #1. Why would you inherit a class and then pass that same class as generic param.
Nevertheless, generic inheritance is supported but its done differently, please check this link, it might give you an idea: Generic Inheritance
Hope this helps.
这篇关于泛型类继承其泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!