Jūs esateŽurnalai / Ernestas Kardzys's blog / C#. Howto get information about class members dynamicaly

C#. Howto get information about class members dynamicaly


ParašėErnestas Kardzys - 2009 Kovo 11

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)); } }

Skelbti naują komentarą

Šio laukelio turinys bus laikomas privatus ir nerodomas viešai.
  • Web puslapiu adresai ir el. pašto adresai automatiškai tampa nuorodomis.
  • Leidžiamos HTML žymės: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Linijos ir paragrafai atskiriami automatiškai
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. The supported tag styles are: <foo>, [foo].

Daugiau informacijos apie teksto formatavimą

CAPTCHA
Šis klausimas yra skirtas įsitikinti, jog jūs esate žmogus, ir sustabdyti automatinį šlamšto siuntimą.
9 + 7 =
Išspręskite šią paprastą matematinę užduotį ir įveskite atsakymą. Pvz., jei užduotis yra 1+3, įveskite 4.