Kategorie szkoleń | Egzaminy | Kontakt
  • 1
  • 0
  • 42

Mam przykładowy obiekt klasy Person:

 

 class Person
        {
            public Person(int age, string name)
            {
                Age = age;
                Name = name;
            }
            public int Age { get; set; }
            public string Name { get; set; }
        }

        static void Main(string[] args)
        {

            var person = new Person(6, "Bartek");

            
        }

 

W jaki sposób pobrać wartość atrybutu, ale posługując się nazwą?

 

 

Uczestnik szkolenia
  • Zapytał
  • @ Uczestnik szkolenia | 09.01.2015

Odpowiedź (1)

  • 2

W tym celu należy skorzystać z mechanizmu refleksji:

 

public static Object GetFieldValue(object source, string propName)
        {
            var value = source.GetType().GetProperties().Single(p => p.Name == propName).GetValue(source);

            return value;
        }

 

a następnie wywołać:

 

var name = GetFieldValue("Name");

 

  • Odpowiedział
  • @ | 09.01.2015
  • TRENER ALTKOM AKADEMII