C#如何动态的创建带参数的构造函数的类,将类作为变量动态创建

C#如何动态的创建带参数的构造函数的类,将类作为变量动态创建

本文章,Jemi会教大家如何动态的创建并使用一个类。
1)申明两个类
2)使用Type 和Activator.CreateInstance(type, parameters)动态创建带构造函数的类。
3)使用它

//声明Dog类
public class Dog
{
     string name;
     int age;
     Dog(name,age)
     {
      	name=n;
      	age=a;
     }
     public void info()
     {
        Console.Writeline($"Dog name{name} age{age}");
     }
}
//声明Cat类
public class Cat
{
     string name;
     int age;
     Cat(name,age)
     {
       name=n;
       age=a;
     }
     public void info()
     {
        Console.Writeline($"Cat name{name} age{age}");
     }
}
void main()
{
    Type type;
    type = typeof(Cat);
    //You want to adopt Dog
    if (true)
        type = typeof(Dog);
    object[] parameters = new object[2];
    parameters[0] = "我的小可爱";
    parameters[1] = 2; 
    //使用Activator.CreateInstance(type, parameters)动态创建你的类 
    using (dynamic mypet = Activator.CreateInstance(type, parameters))
    {
        //调用其中的方法
        mypet.info();
    }

}

你可能会遇到这样的错误:

CS0656 缺少编译器要求的成员“Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create”

解决方案:
https://blog.csdn.net/mango_love/article/details/86063107

你可能感兴趣的:(C#)