Creating a C # attribute that intercepts the getter and setter property

As part of my API, I have an abstract BaseEntity class. I would like to provide a way to somehow connect to the new properties that are introduced in the descendants of this class. I thought:

public class MyEntity : BaseEntity
{
    [DataElement]
    public int NewProperty { get; set; }
}

If I could write an attribute DataElementthat would connect to getter and setter, then my API would be notified of this property upon access.

Is it possible?

UPD: I will try to explain where it came from. I have this BaseEntity which has no data in itself. His descendants will declare what data they can store as properties. I want to be able to iterate all the data that an object has (in order to save them in a database in a very specific form). One way to do this is by reflection. But I was thinking about doing this using attributes that will log data whenever the resource is accessed.

+4
source share
2 answers

Of course, it will look something like this:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class DataElementAttribute : Attribute 
{ }

, , . ( , ).

        Assembly assembly = Assembly.GetExecutingAssembly();
        foreach (Type type in assembly.GetTypes())
        {
            IList<PropertyInfo> properties = type.GetProperties();
            foreach (PropertyInfo pi in properties)
            {
                if (type.IsDefined(typeof(DataElementAttribute), false))
                {
                    // Perform Logic
                }
            }
        }

- , : , ?

MSIL . : http://www.codeproject.com/Articles/37549/CLR-Injection-Runtime-Method-Replacer

+5

, / .

, ISerializable:

public abstract class BaseEntity
{
    public void SaveToDatabase()
    {
        var objectData = new Dictionary<string, object>();
        this.GetObjectData(objectData);
        DatabaseManager.Save(objectData);
    }

    public void LoadFromDatabase(Dictionary<string, object> data)
    {
        this.SetObjectData(data);
    }

    protected abstract void GetObjectData(Dictionary<string, object> data);

    protected abstract void SetObjectData(Dictionary<string, object> data);
}

public class MyEntity : BaseEntity
{
    public int NewProperty { get; set; }

    protected override void GetObjectData(Dictionary<string, object> data)
    {
        data.Add("NewProperty", this.NewProperty);
    }

    protected override void SetObjectData(Dictionary<string, object> data)
    {
        this.NewProperty = (int)data["NewProperty"];
    }
}
+1

Source: https://habr.com/ru/post/1527878/


All Articles