jeudi 22 avril 2021

Iis it possible to codify a collection (or enumeration) of class properties?

I am using reflection to compare objects of a given class. I only want to compare certain properties. Right now I have a simple collection of strings with the names of the properties that I want to compare.

Something like:

public static readonly ICollection<string> PROPERTIES_TO_COMPARE = new List<string>()
{
     "Name",
     "Phone"
};

Then I use it doing something like:

PropertyInfo[] properties = typeof(MyClass).GetProperties();
foreach (PropertyInfo property in properties)
{
     if (PROPERTIES_TO_COMPARE.Contains(property.Name))
     {
         //compare
     }
 }

But if next month I change the property name from "Phone" to "PhoneNumber" I will need to remember to edit the collection of properties. I do not find myself to be that trustworthy.

Is there a better way? Perhaps something similar to nameof(varible), so the compiler can help me? Or perhaps my entire approach is wrong?

Update: This is what I need to do (ideally with less code):

 if (oldVersion.Name != newVersion.Name)
 {
        changes.Add(new Change()
        {
              FieldName = nameof(oldVersion.Name),
              OldValue = oldVersion.Name,
              NewValue = newVersion.Name
        });
  }

  if (oldVersion.Phone != newVersion.Phone)
  {
        changes.Add(new Change()
        {
             FieldName = nameof(oldVersion.Phone),
             OldValue = oldVersion.Phone,
             NewValue = newVersion.Phone
        });
  }
  // and 15 properties more




Aucun commentaire:

Enregistrer un commentaire