遍历扩展类列表并动态创建对象

时间:2019-06-14 12:30:03

标签: c# class derived-class

我想遍历扩展“ A”类并创建扩展类类型的对象的类列表。

有没有办法替换“ new className();”中的className?带有变量还是必须使用switch语句创建不同类型的对象?

List <A> listOfSubClasses; //A list of classes that all extend "A"
List <A> objects; //List to hold created objects
int[] variable; 
foreach (A subClass in listOfSubClasses){
    for (int i = 0; i < 3; i++){ //Let's say I want to create 3 objects of every class
        objects.Add (new subClass()); //This is the line my question refers to
        objects[objects.Count - 1].someParameter = variable[i];
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用List<Type>存储要实例化的类型,然后使用System.Activator.CreateInstance从该类型创建实例

using System;
using System.Collections.Generic;

public class A
{
    public int someParameter;
}
public class B : A {}
public class C : A {}
public class D : A {}

public class Program
{
    public static void Main()
    {
        List <Type> listOfSubClasses = new List<Type>
        {
            typeof(B),
            typeof(C),
            typeof(D)
        };
        List <A> objects = new List<A>();

        int[] variable = { 1, 2, 3 }; 
        foreach (var subClass in listOfSubClasses) {
            for (int i = 0; i < 3; i++) {
                objects.Add((A)Activator.CreateInstance(subClass));
                objects[objects.Count - 1].someParameter = variable[i];
            }
        }
    }
}

答案 1 :(得分:0)

您可以为此使用反射。 (我尚未在计算机上检查此解决方案,因此可能会有细微的差异。)

using System;

// ...

List<Type> listOfSubClasses =
    from assembly in AppDomain.CurrentDomain.GetAssemblies()
    from type in assembly.GetTypes()
    where type.IsSubclassOf(typeof(A))
    select type;

List<A> objects;
int[] variable; 
foreach (Type subClass in listOfSubClasses) {
    for (int i = 0; i < 3; i++) {
        objects.Add((A)Activator.CreateInstance(subClass));
        objects[objects.Count - 1].someParameter = variable[i];
    }
}

Activator.CreateInstance使用默认的构造函数创建对象,但是如果您需要其他东西,还会有其他重载。

提供类的所有子类的解决方案是here