C#反射获取某个类的字段属性方法

版权声明:转载 请说明 https://blog.csdn.net/qq2512667/article/details/82964953

 在LitJson里面有个类是JsonMapper 映射

有些方法 

        public static T ToObject<T>(JsonReader reader);
        public static T ToObject<T>(TextReader reader);
        public static T ToObject<T>(string json);

 //使用以上的方法要注意 T类中 字段或者属性名字 必须是公开的 且和json中的key值保持一致;  如果数据很多可以用List<T>

或者 T[ ] 来取得。

就是通过Reflection 反射 取得 字段 或者属性,进行匹配的

下面是 泛型类通过反射 去得字段属性的方法  可以传个string 进行处理。

  public static void PrintAttr<T>() where T :new()
        {
            T a = default(T);

            a = new T();
            Type t = a.GetType();

            //都是公共的
            FieldInfo[] fieldInfos = t.GetFields();//字段

            PropertyInfo[] propertyInfos = t.GetProperties();//属性

            MethodInfo[] methodInfos = t.GetMethods();//方法

            WriteLine("属性个数:" + propertyInfos.Count());
            foreach (PropertyInfo pInfo in propertyInfos)
            {
                WriteLine("属性:" + pInfo.ToString());

            }
            WriteLine("字段总数:" + fieldInfos.Count());
            foreach (var item in fieldInfos)
            {
                WriteLine("字段" + item.ToString());  //获取字段
            }

            WriteLine($"方法总数:{ methodInfos.Count()}");
            foreach (MethodInfo item in methodInfos)
            {
                WriteLine($"方法:{item.ToString()}");
            }
            WriteLine(t.Assembly);
        }

猜你喜欢

转载自blog.csdn.net/qq2512667/article/details/82964953