Jūs esate

C#. Howto get information about class members dynamicaly

Last weekend I had a problem. I have two different classes:
class ClassWithData2 { public ClassWithData2() { } private string _Field; public string Field { get { return _Field; } set { _Field = value; } } } class ClassWithData { public ClassWithData() { } private string _Name = null; public string Name { get { return _Name; } set { _Name = value; } } private string _Age; public string Age { get { return _Age; } set { _Age = value; } } }
My problem was: how to pass those two classes to one method and then print what members do they have and what values the class members do have. The code is as follows:
using System.Reflection; // Code... private void Print<T>(T packet) { foreach (PropertyInfo packetInfo in packet.GetType().GetProperties()) { Console.WriteLine(packetInfo.Name + " " + packetInfo.GetValue(packet, null)); } }

Komentuoti