2

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.

If there is any other way to get this done by using another method please let me know.

Thank you.

  • 3
    `GetType()` returns the actual runtime type of the object, even when you call it on a reference to a base class. There would be little point in it otherwise. – 15ee8f99-57ff-4f92-890c-b56153 Aug 21 '19 at 12:52
  • Your question isn't written very clearly. Your title says you want to get fields, but the code you posted involves properties. Regardless, getting the fields or properties of a specific object is a well-known, well-documented operation, and questions related to that have been answered literally hundreds of times on Stack Overflow. See marked duplicates for examples. – Peter Duniho Aug 21 '19 at 16:19
  • Sorry about that! – The Riccardo Aug 22 '19 at 08:59

1 Answers1

2

You´re almost there. All you need to do is to get the properties value on the current instance - the instance on which you´ve called the method:

if(hasAttribute)
{
    var value = property.GetValue(this, null);
}

Apart from this you won´t need generics here. Just use this:

var type = this.GetType();

which returns TestEntity in case of the instance being of your derived type.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111