Generic class that inherits its generic type [duplicate]
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 开发者_如何学Gomust 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.
What you are doing defeats the generic objective.
How can I just use something like this:
Generic<int> intgen = new Generic<int>(); // Impossible
The problem is generic defines a behaviour which is type-unspecific. your generic is type specific since it has to inherit from it. Generic is used to encapsulate a functionality that cannot be expressed in inheritance while you are mixing the two - and I can tell you it ain't gonna be a good mix.
You can't do this because T in the definition of the generic is a type definition and not a real class. I'm not sure what you are trying to accomplish, though, because in my opinion your problem could be solved with a simple inheritance. If you are trying to add some behavior to your class then you can simply use a generic and derive from that:
public class Behavior<T>
{
...
}
public class DerivedBehavior<T> : Behavior<T>
{
...
}
精彩评论