vendredi 23 mars 2018

Empty ReadOnly-List using reflection

I have a custom attribute, that is meant to mark a property to be erased before it is returned:

public HideAttribute:Attribute {}

public class UserData {
  public string Name {get;set;}
  [Hide]
  public string Phone {get;set;}
  [Hide]
  public List<Account> Accounts {get;} = new List<Account>();
}

Now the following code removes the data:

protected void Remove<T>(T someData) {
  foreach(var property in typeof(T).GetProperties()) {
    if (property.GetCustomAttribute<HideAttribute>==null) continue;
    Type t=property.PropertyType;
    if (property.CanWrite) {
      property.SetValue(someData,null) 
    } else if (property.CanRead && t.IsGenericType && t.GetGenericTypeDefinition==typeof(List<>)) {
      property.Empty(someData); // Pseudocode; There is no such method
    }
  }
}

Now what I want is: If the property is not writable, but is a list-type, I want to empty that list.





Aucun commentaire:

Enregistrer un commentaire