C#:Func与继承类型的构造函数(C#: Func with a constructor of an inherited type)

编程入门 行业动态 更新时间:2024-10-25 12:28:36
C#:Func与继承类型的构造函数(C#: Func with a constructor of an inherited type)

正如我们所知,你可以像这样将一个构造函数指向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 type

An 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.

更多推荐

本文发布于:2023-08-06 17:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   类型   Func   type   inherited

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!