正如我们所知,你可以像这样将一个构造函数指向Func<T> :
Func<MyObject> constructor = () => new MyObject(); var newObject = constructor();但是有没有办法为你知道从MyObject继承的对象创建构造函数 ,但是你不知道它的确切类型?
Type inheritedObjectType = obj; // Parameter Func<MyObject> constructor = () => new MyObject(); // as inheritedObjectType var newInheritedObject = constructor; // Should now be of the inherited type使用Activator或任何返回Object的答案不是一个选项。
编辑 :我不知道在编译时派生类型是什么类型。 我只有一个System.Type 。
As we know you can point to a constructor as a Func<T> like this:
Func<MyObject> constructor = () => new MyObject(); var newObject = constructor();But is there a way to make a constructor for an object you know inherits from MyObject, but you don't know its exact type?
Type inheritedObjectType = obj; // Parameter Func<MyObject> constructor = () => new MyObject(); // as inheritedObjectType var newInheritedObject = constructor; // Should now be of the inherited typeAn answer with using Activator or anything returning Object is not an option.
Edit: I don't know what type the derived type is at compile time. I only have a System.Type.
最满意答案
您可以使用表达式树来构建和编译将创建派生类型的委托:
Func<TBase> CreateDelegate<TBase>(Type derived) { var ctor = derived.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new ArgumentException("D'oh! No default ctor."); } var newExpression = Expression.Lambda<Func<TBase>>( Expression.New(ctor, new Expression[0]), new ParameterExpression[0]); return newExpression.Compile(); }你可以简单地调用它,如下所示:
Func<MyBase> create = CreateDelegate<MyBase>(typeof(Derived)); MyBase instance = create();当您缓存该代理时,您将获得最佳性能。
You can use expression trees to build and compile a delegate that will create your derived type:
Func<TBase> CreateDelegate<TBase>(Type derived) { var ctor = derived.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new ArgumentException("D'oh! No default ctor."); } var newExpression = Expression.Lambda<Func<TBase>>( Expression.New(ctor, new Expression[0]), new ParameterExpression[0]); return newExpression.Compile(); }You can simply call it as follows:
Func<MyBase> create = CreateDelegate<MyBase>(typeof(Derived)); MyBase instance = create();When you cache that delegate, you will get maximum performance.
更多推荐
发布评论