Использование рефлексии для вложенного класса - C#
Формулировка задачи:
Здравствуйте. Вопрос такой.
Есть класс, например, public class Class1
в нем куча полей и свойств простых типов (риал, инт, стринг и тд)
и есть поля и свойства типа Class2 (который может состоять как из простых типов, так и из классов)
Нужны методы для получения всех имен свойств (если свойство является классом то необходимо вызывать рефлексию для него, и получить свойства из которых состоит этот класс) и для получения всех значений.
Для получения имен я написал метод:
Правда, очень страшно выглядит, как бы сделать покрасивее? и избавится от константы? она все портит(((
Для получения значений:
Тут не могу додумать, а как вызывать функцию для вложенного класса (как в примере с получением имен)
В методе выше я передавал тип, а тут нужно передавать объект. как это сделать?
Извиняюсь за глупый вопрос.
Помогите, пожалуйста(((
Листинг программы
- public static void GetNamesOfClassProps1(Type clType, out string[] names)
- {
- PropertyInfo[] getsProp = clType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
- int i = 0;
- string []names1 = new string[getsProp.Length];
- Type[] types = new Type[getsProp.Length];
- // Как избавится от константы в строчке ниже?
- string[] names2 = new string[2];
- string[] temp = new string[getsProp.Length+ names2.Length];
- foreach (PropertyInfo propInfo in getsProp)
- {
- names1[i] = propInfo.Name;
- types[i] = propInfo.PropertyType;
- if (types[i].IsClass == true)
- {
- GetNamesOfClassProps1(types[i], out names2);
- }
- i += 1;
- }
- for (int j = 0; j < names1.Length; j++)
- temp[j] = names1[j];
- for (int j = 0; j < names2.Length; j++)
- {
- if (names2[j] != null)
- temp[j + names1.Length] = names2[j];
- }
- names = temp;
- }
Листинг программы
- public static void ReadFromClassProps(object elClass, out object[] readed)
- {
- Type clType = elClass.GetType();
- PropertyInfo[] getsProp = clType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
- readed = new object[getsProp.Length];
- int i = 0;
- foreach (PropertyInfo propInfo in getsProp)
- {
- if (propInfo.CanRead)
- {
- readed[i] = propInfo.GetValue(elClass);
- }
- i += 1;
- }
- }
Решение задачи: «Использование рефлексии для вложенного класса»
textual
Листинг программы
- class Class1
- {
- public int Prop1 { get; set; } = 1;
- public byte Prop2 { get; set; } = 2;
- public long Prop3 { get; set; } = 3;
- public float Prop4 { get; set; } = 4.5f;
- public Class2 Prop5 { get; set; } = new Class2();
- public string Prop6 { get; set; } = "1234";
- public List<string> GetPropertyNames()
- {
- List<string> result = new List<string>();
- result.AddRange(GetPropertyNames(GetType()));
- return result;
- }
- public List<string> GetPropertyNames(Type type)
- {
- List<string> result = new List<string>();
- PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
- foreach(var prop in properties)
- {
- result.Add(prop.Name);
- if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
- {
- foreach(var prop2 in GetPropertyNames(prop.PropertyType))
- {
- result.Add(prop.Name + "." + prop2);
- }
- }
- }
- return result;
- }
- public List<object> GetPropertyValues()
- {
- List<object> result = new List<object>();
- result.AddRange(GetPropertyValues(GetType(), this));
- return result;
- }
- public List<object> GetPropertyValues(Type type, object obj)
- {
- List<object> result = new List<object>();
- PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
- foreach (var prop in properties)
- {
- var obj2 = prop.GetValue(obj);
- result.Add(obj2);
- if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
- {
- foreach (var prop2 in GetPropertyValues(prop.PropertyType, obj2))
- {
- result.Add(prop2);
- }
- }
- }
- return result;
- }
- public Dictionary<string, object> GetPropertyNamesAndValues()
- {
- Dictionary<string, object> result = new Dictionary<string, object>();
- foreach (var kv in GetPropertyNamesAndValues(GetType(), this))
- result.Add(kv.Key, kv.Value);
- return result;
- }
- public Dictionary<string, object> GetPropertyNamesAndValues(Type type, object obj)
- {
- Dictionary<string, object> result = new Dictionary<string, object>();
- PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
- foreach (var prop in properties)
- {
- var obj2 = prop.GetValue(obj);
- result.Add(prop.Name, obj2);
- if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
- foreach (var prop2 in GetPropertyNamesAndValues(prop.PropertyType, obj2))
- result.Add(prop.Name + "." + prop2.Key, prop2.Value);
- }
- return result;
- }
- public void Print()
- {
- //foreach(var prop in GetPropertyNames())
- //{
- // Console.WriteLine(prop);
- //}
- //foreach (var val in GetPropertyValues())
- //{
- // Console.WriteLine(val);
- //}
- foreach (var prop in GetPropertyNamesAndValues())
- {
- Console.WriteLine(prop.Key + ": " + prop.Value);
- }
- }
- }
- class Class2
- {
- public int Prop1 { get; set; } = 6;
- public byte Prop2 { get; set; } = 7;
- public long Prop3 { get; set; } = 8;
- public float Prop4 { get; set; } = 9;
- public Class3 Prop5 { get; set; } = new Class3();
- public string Prop6 { get; set; } = "458enb57enb5e";
- }
- class Class3
- {
- public int Prop1 { get; set; }
- public byte Prop2 { get; set; }
- public long Prop3 { get; set; }
- public float Prop4 { get; set; }
- public string Prop6 { get; set; }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д