动态创建派生类型的实例
本文关键字:实例 类型 派生 创建 动态 | 更新日期: 2023-09-27 18:31:17
因此,让我们假设我们有一个Base程序集和一个Custom-Assembly,其中Base中的每个类型都可以或可能不会被覆盖。所以我有一些代码可以创建一些基类型的深度嵌套结构。现在,如果我想覆盖此结构中的某个单一类型,则必须覆盖整个结构才能实例化它。为了简化这个过程,我使用了一个工厂(如此处建议的)来构建我的内部类型。
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); }
}
现在,我可以在基接口中调用工厂方法来创建内部类型。如果这个内部类型是在我的自定义程序集中派生的,我会得到该类型的实例而不是基类型。
现在我的问题:据我所知,通过反射创建实例可能需要一些时间。因此,我正在循环中创建此类实例,这可能会成为与性能相关的问题。我知道您可以使用 LINQ 表达式加快调用方法的速度(尽管我自己从来没有这样做过)。这指向实际方法。因此,我们可以直接调用可能比使用 MethodInfo.Invoke
快得多的方法。是否有任何类似的方法可以通过声明某种指向构造函数而不是方法的指针来创建新实例?
谢谢你的:)
您可以使用泛型来执行此操作:
public class MyFactory<T> where T : MyBaseClass
{
public static T Create(string name) { return new T{ Name = name }; }
}