如果类型具有构造函数参数,如何在字典中创建类型变量的新对象 c#

how to make a new object of an type variable in a Dictionary if the type has constructor arguments c#

class baseClass
{         
    public baseClass(int x,int y) {}
}
class class1 : baseClass
{    
    public class1(int x,int y) : base (x,y) {}
}
public void Main()
{

    Dictionery<int,Type> classes = new Dictionery<int,Type>();
    classes.add(1,typeof(Class1));

    baseClass x = new classes[1] (10 , 12); // doesent work

    //tried
    baseClass x = Activator.CreateInstanceFrom(classes[2](10, 12))
    //tried
    baseClass x = Activator.CreateInstanceFrom(classes[2], 10, 12)
}

我找到这个 post : Store class definition in dictionary, instance later

和一个回答说:如果你的类型有接受相同参数的构造函数,你可以在 dict["A"]

之后添加参数

但是,这样做的语法是怎样的?

我只想在 post 上发表评论,但我没有这样做的声誉...:/

您可以使用这样的this overload of CreateInstance创建您需要的对象:

baseClass x = (baseClass)Activator.CreateInstance(classes[1], 10, 12);

在这种情况下,有 3 个参数传递给 CreateInstance 方法:class 类型和参数数组。

您还需要将其转换为 baseClass,因为 CreateInstance 方法 returns object

我经历了 post 但我也不确定。我只是想知道如何在创建字典实例时创建自定义 class 并传递参数。我只是假设您在创建字典实例时知道每个 class 需要的参数。请通过以下代码:

class Program
    {
        public static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, TypeCreator>();
            dictionary.Add("A", new TypeCreator(typeof(CustomA),"parameter1"));
            dictionary.Add("B", new TypeCreator(typeof(CustomB), "parameter1", "parameter2"));

            var instance = dictionary["A"].GetInstance();
        }        
    }

    public class TypeCreator
    {
        public TypeCreator(Type type, params object[] args)
        {
            CustomType = type;
            Params = args;
        }
        public Type CustomType { get; set; }
        public object[] Params { get; set; }

        public Object GetInstance()
        {
            return Activator.CreateInstance(CustomType, Params);
        }
    }

    public class CustomA
    {
        public CustomA(string param1)
        {

        }
    }

    public class CustomB
    {
        public CustomB(string param1, string param2)
        {

        }
    }