What are the good reasons to wish that .NET generics could inherit one of the generic parameter types?

后端 未结 8 1424
旧时难觅i
旧时难觅i 2020-12-06 04:40

This post is in continuation of this one.

I am trying to understand if I am the only one who misses and needs the ability of a .NET generic type to inherit one of it

8条回答
  •  囚心锁ツ
    2020-12-06 05:35

    Every now and then I stumble upon an implementation issue, where I deeply regret that C cannot inherit T. Unfortunately, I have never recorded these issues and so I can describe just the most recent one - the one I have stumbled upon right now. So here it is:

    Our system is extensible through metadata, which becomes available at run-time. The metadata is translated to a type dynamically generated at run-time using Reflection.Emit. Unfortunately, the dynamically generated type has to satisfy the following conditions:

    1. It must derive from some other type, provided as a parameter to the dynamic type creator. This type is called the ancestor type and is always a statically compiled type.
    2. It must implement several interfaces, say IDynamicObject (our interface), System.ComponentModel.INotifyPropertyChanged and Csla.Core.IMobileObject. Note, that this condition places certain constraints on the ancestor type. For instance, the ancestor type may not implement the IDynamicObject interface, except if all the interface methods are implemented abstractly. There are other constraints, all of which must be checked.
    3. It should (and it does) override the object methods Equals, ToString and GetHashCode.

    Currently, I had to use Reflection.Emit to emit all the IL code to satisfy these conditions. Of course, some tasks may be forwarded to statically compiled code. For instance, the override of the object.Equals(object) method invokes DynamicObjectHelper(IDynamicObject, IDynamicObject) which is a statically compiled C# code doing the largest bulk of the work of comparing two dynamic objects for equality. But this is more of an exception than the rule - most of the implementation is emitted, which is a pain in the butt.

    Would not it be great to be able to write a generic type, like DynamicObjectBase which will be instantiated with the ancestor type and serve as the actual base type of the dynamically generated type? As I view it, the generic type DynamicObjectBase could implement much of the dynamic type requirements in a statically compiled C# code. The dynamically emitted type would inherit it and probably, just override a few simple virtual methods.

    To conclude, my compelling reason is that letting C inherit from T would greatly simplify the task of emitting dynamic types.

提交回复
热议问题