创建挂钩到属性的getter和setter的C#属性

Dmy*_*nko 5 c# aop attributes

作为我的API的一部分,我有一个抽象的BaseEntity类.我想提供一种方法以某种方式挂钩在这个类的后代中引入的新属性.我在想的是这个:

public class MyEntity : BaseEntity
{
    [DataElement]
    public int NewProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如果我可以编写一个DataElement挂钩getter和setter 的属性,那么我的API将在访问时知道这个属性.

这可能吗?

UPD:我会试着解释它的来源.我有这个BaseEntity本身没有任何数据.它的后代将声明它们可能作为属性保存的数据.我希望能够遍历对象具有的所有数据(以非常特定的形式将其存储在数据库中).一种方法是反思.但是我想通过在访问属性时注册数据的属性来做这件事.

Jef*_*eff 5

当然,它看起来类似于以下内容:

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

您必须使用反射枚举属性以查看属性是否包含该属性.(这引出了一个问题,你真的需要这个属性).

        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
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

然而,将逻辑注入setter是一项不同的任务,需要在编译完成: 为什么编译后代码注入比预编译代码注入更好?

注入MSIL并不容易.看看这个示例代码:http: //www.codeproject.com/Articles/37549/CLR-Injection-Runtime-Method-Replacer