mercredi 21 août 2019

Is there a way for a class to access fields in classes that inherit from it using reflection?

What I'm trying to do is have a class that I can inherit from and be able to track changes to properties.

I have this base class called TrackedEntity.

I then create another class TestEntity that inherits from TrackedEntity.

On my TestEntity class I have marked one of my fields with an attribute that I called CompareValues.

TrackedEntity

  public class TrackedEntity {
        public void GetCompareValues<T> () {

            var type = typeof (T);
            var properties = type.GetProperties ();

            foreach (var property in properties) {

              var attribute = (CompareValues[]) property.GetCustomAttributes 
                                             (typeof(CompareValues), false);

              var hasAttribute = Attribute.IsDefined (property, typeof 
                                   (CompareValues));

            }
        }
    }

TestEntity

public class TestEntity : TrackedEntity
    {
        public int one { get; set; }
        [CompareValues]
        public int two { get; set; }
        public int three { get; set; }
    }

CompareValues attribute:

 [AttributeUsage ( AttributeTargets.Property | 
                      AttributeTargets.Field,
                      Inherited = true)]
    public class CompareValues : Attribute {
        public CompareValues () { }
    }

I can then do this

var test  = new TestEntity ();
test.GetCompareValues<TestEntity> ();

In my GetCompareValues method I can find which fields in TestEntity use my CompareValues attribute.

I am trying to find a way to access the value of the fields that have the CompareValues attribute so that I can track the changes and log information about it.

Thank you.





Aucun commentaire:

Enregistrer un commentaire