OOP 反射学习笔记之一

啥是反射
动态获取类型信息 动态创建对象 动态访问成员的过程。

反射的作用

  1. 了解类型信息
  2. 动态创建类型实例
  3. 动态访问实例的成员

常用类

取得数据类型Type
如何得到Type
方式一:Type.GetType(“类型全名”);
适合于类型的名称已知
方式二:obj.GetType();
适合于类型名未知,类型未知,存在已有对象
方式三:typeof(类型)
适合于已知类型
方式四:Assembly.Load(“XXX”).GetType(“名字”);
适合于类型在另一个程序集中
Type类常用Get系列方法 Is系列属性

System.Reflection 命名空间
	MethodInfo(方法)
		重要方法: Invoke
	PropertyInfo(属性)
		重要方法:SetValue GetValue
	FieldInfo(字段)
		重要方法:SetValue GetValue
	ConstructInfo(构造方法)
		重要方法:Invoke

动态创建对象
Activator.CreateInstance(string 程序集名称,string 类型全名).Unwarp()
Activator.CreateInstance(Type type);

Assembly assembly = Assembly.Load(程序集);
assembly.CreateInstance(Type);
//找到有参构造方法,动态调用构造方法
type.GetConstructor(typeof(string)).Invoke()

OOP 反射学习笔记之一

 static void Main(string[] args)
        {
            User user = new User();

            //获取类型 Type
            //第一种方式
            Type type= Type.GetType("反射.User");//命名空间.类名
            //第二种方法
            Type type1 = user.GetType();
            //第三种方式 
            Type type2 = typeof(User);

            //创建对象
           object instance= Activator.CreateInstance(type);
            //访问成员
            PropertyInfo  IdProperty=type.GetProperty("ID");
            //有可能输入的是strin double 等等类型
            //IdProperty.SetValue(instance, 1000);
            //转换成ID属性的类型
            object IdValue=Convert.ChangeType("1000", IdProperty.PropertyType);
            IdProperty.SetValue(instance, IdValue);
            PropertyInfo LoginpropertyInfo = type.GetProperty("Name");
            //同理也是将zxx转换
            object NameValue = Convert.ChangeType("zxx", LoginpropertyInfo.PropertyType);
            LoginpropertyInfo.SetValue(instance, NameValue);
            MethodInfo printMethod = type.GetMethod("print");
            printMethod.Invoke(instance, null);//null表示没有参数
            Console.ReadLine();
        }
    }
   public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public void print()
        {
            Console.WriteLine(ID.ToString());
            Console.WriteLine(Name);
        }
    }