反射动态创建对象_Json为例

来源:互联网 发布:淘宝网夏装女装 编辑:程序博客网 时间:2024/06/16 13:14

1. 取得数据类型Type

方式一:Type.GetType(“类型全名”);

                   适合于类型的名称已知

方式二:obj.GetType();

                   适合于类型名未知,类型未知,存在已有对象

方式三:typeof(类型)

                   适合于已知类型

方式四:Assembly.Load(XXX).GetType(“名字”);

         适合于类型在另一个程序集中

 

实例

Type type =Type.GetType("Day07.MainCity");

           //Type type = city.GetType();

           //Type type = typeof(MainCity);

2. 动态创建对象

Activator.CreateInstance(string 程序集名称,string 类型全名)

 Activator.CreateInstance(Type type);

 

Assembly assembly = Assembly.Load(程序集);

assembly.CreateInstance(Type);

 

//找到有参构造方法,动态调用构造方法

type.GetConstructor(typeof(string)).Invoke()

 

实例

//动态创建对象

           object obj = Activator.CreateInstance(type);

 

3.Type类常用Get系列方法 Is系列属性。

2.      MethodInfo(方法)

重要方法: Invoke

 

MethodInfo method = type.GetMethod("PrintName");

method.Invoke(obj, null);

           

MethodInfo methodFun1 =type.GetMethod("Fun1", BindingFlags.NonPublic |BindingFlags.Instance);

methodFun1.Invoke(obj, null); 

 

3.      PropertyInfo(属性)

         重要方法:SetValueGetValue

4.      FieldInfo(字段)

         重要方法:SetValueGetValue

5.      ConstructInfo(构造方法)

         重要方法:Invoke

 

 

 

 

 

实例

//获取类型信息

           PropertyInfo property = type.GetProperty("Name");

           property.SetValue(obj, "abc");

           //property.SetValue(obj, "100");

 

 

 

 

属性类型转换

 

 

//1.属性类型:

property.PropertyType 

//2.字符串转换为属性类型:

           //Convert.ChangeType("100", property.PropertyType);

 

 

 

 

 

 

 

 

 

 

 

 

 

      /*

        Json 字符串格式

        *  {"Name" : "abc","HP":"100"}           

        * 

        JsonHelper

        -- c# 对象 -->  Json字符串

 

 

        -- Json字符串 -->  c#对象

        * (提示

        *    1. 泛型方法

        *    2.

        * )

        

        */

 

 

 

 

 

 

反射与缓存结合使用

 

 

 

 

 

转换方法实现

        //-- c# 对象 -->  Json字符串

       //{"Name" : "abc","HP":"100"}           

       public static string ObjectToString(object obj)

       {

           StringBuilder builder = new StringBuilder();

           builder.Append("{");

           //获取类型信息

           Type type = obj.GetType();

           //获取当前类型所有属性

           foreach (var p in type.GetProperties())

           {

               builder.AppendFormat("\"{0}\":\"{1}\",",p.Name, p.GetValue(obj));

           }

           builder.Remove(builder.Length- 1, 1);

           builder.Append("}");

           return builder.ToString();

       }

        

        //-- Json字符串 -->  c#对象

        //{"Name" : "abc","HP":"100"} 

       public static T StringToObject<T>(string jsonString)//whereT:new()

       {

           //创建对象

           //T obj = new T();

           Type type = typeof(T);

           object obj = Activator.CreateInstance(type);

           //根据字符串为属性赋值

           //{"Name" : "abc","HP":"100"} 

           //去除字符 {       "      }

           jsonString = jsonString.Replace("{", "").Replace("\"","").Replace("}", "");

           //Name:abc,HP:100,MaxHP:100

           string[] keyValue = jsonString.Split(',', ':');

           for (int i = 0; i < keyValue.Length; i+=2)

           {

                  //keyValue[i]   keyValue[i+1]

               var property =type.GetProperty(keyValue[i]);

                object propertyVal =Convert.ChangeType(keyValue[i + 1], property.PropertyType);

                property.SetValue(obj,propertyVal);

           }

           return (T)obj;

       }

    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

原创粉丝点击