动态创建派生类型的实例

时间:2014-11-20 14:15:06

标签: c# linq reflection

因此,假设我们有一个Base-Assembly和一个Custom-Assembly,Base中的每个类型都可以被覆盖,也可以不被覆盖。所以我有一些代码可以创建一些基类型的深层嵌套结构。现在,如果我想在这个结构中覆盖一些单一类型,我将不得不覆盖整个结构来实例化它。为了简化这个过程,我使用了一个构建我的内部类型的工厂(如建议here)。

public class MyFactory
{
    private Assembly _customAssembly = // get custom-assembly;
    private Type _actualType = null;
    private static MyFactory _instance = new MyFactory();

    private MyFactory()
    {
        // if we have custom assembly we search for classes that derive from our base-type
        if (this._customAssembly != null) this._actualType = this._customAssembly.GetTypes().SingleOrDefault(x => x.BaseType == typeof(MyClass));
        // no derived type found so use the base-type
        if (this._actualType == null) this._actualType = typeof(MyClass);
    }

    /// <summary>
    /// Gets an instance of either <see cref="MyClass"/> or an instance of a derived type of this class if there is any within the custom-assembly
    /// </summary>
    public static MyClass Create(string name) { return (MyClass)Activator.CreateInstance(MyFactory._instance._actualType, name); }
}

现在我可以在我的base-interface中调用factory-method来创建内部类型。如果这个内部类型是在我的自定义程序集中派生的,那么我得到的是该类型的实例而不是基类型。

现在我的问题:据我所知,通过反射创建实例可能需要一些时间。因此,我在循环中创建此类实例,这可能成为与性能相关的问题。我知道你可以使用LINQ-Expressions来调整方法的速度(虽然我从来没有自己做过)。这指向实际的方法。因此,我们可以直接调用方法,这可能比使用MethodInfo.Invoke快得多。有没有类似的方法可以通过声明某种构造函数的指针而不是方法来创建新实例?

谢谢你:)

1 个答案:

答案 0 :(得分:0)

您可以使用泛型来执行此操作:

public class MyFactory<T> where T : MyBaseClass
{
    public static T Create(string name) { return new T{ Name = name }; }
}