C#:使用继承类型的构造函数的Func

Seb*_*son 3 c# lambda constructor func inherited

我们知道你可以Func<T>像这样指向一个构造函数:

Func<MyObject> constructor = () => new MyObject();
var newObject = constructor();
Run Code Online (Sandbox Code Playgroud)

但有没有办法为你知道从MyObject继承的对象制作一个构造函数,但你不知道它的确切类型?

Type inheritedObjectType = obj; // Parameter
Func<MyObject> constructor = () => new MyObject(); // as inheritedObjectType
var newInheritedObject = constructor; // Should now be of the inherited type
Run Code Online (Sandbox Code Playgroud)

使用Activator或返回任何东西的答案都不Object是一种选择.

编辑:我不知道派生类型在编译时是什么类型.我只有一个System.Type.

Ste*_*ven 7

您可以使用表达式树来构建和编译将创建派生类型的委托:

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();
}
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式调用它:

Func<MyBase> create = CreateDelegate<MyBase>(typeof(Derived));

MyBase instance = create();
Run Code Online (Sandbox Code Playgroud)

缓存该委托时,您将获得最大性能.