jeudi 2 mai 2019

How do I use C# reflection to get a list of values of an object's fields that match a particular type?

I've defined a boolean property, personProperty for a class, Person, in which I want the getter, get{} to call a private method, personMethod(int arg) on each integer field value that's defined in Person (in this case _age, _phoneNumber). It should ignore all other types like readingList.

This is so that if I were to add another integer field to Person (or modify or delete any Person field names), I would not have to update the definition of personProperty which, by design choice, depends on all integer fields of the Person class (i.e., it is never the case that the developer will introduce an int field that he doesn't want personMethod to run against).

public Person
{
   private int _age;
   public int _phoneNumber;
   // protected int _futureInt;
   Dictionary<string> _readingList = new Dictionary<string>();

   public bool personProperty
   {
       get
       {
           // ...
           bool personPropertyReturnValue; 
           List<bool> resultList = new List<bool>();
           foreach(int personFieldValue in LISTOFPERSONINTS)
           {
               bool result = personMethod(personFieldValue);
               resultList.Add(result);
           }
           // Do stuff with `resultList` that'll initialize personPropertyReturnValue;
           return personPropertyReturnValue;
       }
   }

    private bool personMethod(int arg)
    {
       bool returnValue = true;
       // Do stuff to initialize `returnValue`
       return returnValue;
    }
}

I need to know what I should substitute for LISTOFPERSONINTS so that it returns an iterable over the values stored in _age, _phoneNumber (and all other future int, like _futureInt defined in Person).





Aucun commentaire:

Enregistrer un commentaire