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

Iterating through list of extended classes and dynamically creating objects

我想遍历扩展 class "A" 的 classes 列表并创建扩展 classes' 类型的对象。

有没有办法用变量替换 "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];
    }
}

您可以使用 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];
            }
        }
    }
}

您可以为此使用反射。 (我没有在我的机器上检查这个解决方案,所以可能会有细微的差别。)

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 使用默认构造函数创建对象,但如果您需要其他东西,还有其他重载。

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