反射2 创建指定对象
首先给要创建的类增加构造函数
namespace ReflectionBLL { public class Person { private int _Id; private string _Name; private int _Age; public Person() { Console.WriteLine("Person类构造函数"); } public Person(string name) { Console.WriteLine("Person类构造函数,我的名字是" + name); } public void CreatePerson() { Console.WriteLine("Person类方法CreatePerson"); } } }
1.通过反射创建,调用无参构造函数
Type type = assembly.GetType("ReflectionBLL.Person");//必须带上命名空间 Person personObj = (Person)Activator.CreateInstance(type);//相当于我们new一个对象,这种的前提就是我们其实知道要实例化的对象并且引用了,不然我们也没法调用对象里的方法。 personObj.CreatePerson();
2.有参数的
Type type = assembly.GetType("ReflectionBLL.Person");//必须带上命名空间 Person personObj = (Person)Activator.CreateInstance(type,new object[] { "张三"});//相当于我们new一个对象,这种的前提就是我们其实知道要实例化的对象并且引用了,不然我们也没法调用对象里的方法。 personObj.CreatePerson();
3.调用私有构造函数
我们将原来的无参构造函数改成私有的,这个时候运行之前的代码就会报错,提示找不到相应的构造函数,其实是因为私有了。
private Person() { Console.WriteLine("Person类构造函数"); }
修改调用方法,第二个参数true,就可以调用私有的构造函数,但是如果是有参数的,就没有相应的CreateInstance重载方法。
//调用私有构造函数 Type type = assembly.GetType("ReflectionBLL.Person");//必须带上命名空间 Person personObj = (Person)Activator.CreateInstance(type,true);//相当于我们new一个对象,这种的前提就是我们其实知道要实例化的对象并且引用了,不然我们也没法调用对象里的方法。 personObj.CreatePerson();