I'm basically wanting to do this:
class UILockable<T> : T where T : UIWidget { }
However, this doesn't work. I've seen people recommend that you do this:
class UILockable<T> where T : UIWidget { private T _base; }
This would require me to override each function UILockable would need and forward it to T. This is impossible since T may derive from UIWidget and have unique abstract/virtual methods of its own.
Is there no way to simply inherit from T?
You cannot inherit a generic type. // class Derived20 : T {}// NO!
Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
Generics were added in C# 2.0. Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types that they store or use. A generic collection class might use a type parameter as a placeholder for the type of objects that it stores.
You can't inherit from the generic type parameter. C# generics are very different from C++ templates. Inheriting from the type parameter requires the class to have a completely different representation based on the type parameter, which is not what happens with .NET generics. They are identical at the IL and native level (for all reference type arguments).
Think about it this way: When Type B inherits from type A, you're declaring that B is similar to A (where similarity means that you can use B everywhere you expect to use A). Now because such similarity is not symmetric you have that B is similar to A but A is not similar to B. Furthermore, B and C can both be similar to A (i.e. they both descend from A) without being similar to each other.
So what you want to declare is that Unlockable is similar to everything that is similar to UIWidget, but that's impossible because type similarity is not transitive (i.e. if B is similar to A and C is similar to A you can't say B is similar to C).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With