作为我的 API 的一部分,我有一个抽象的 BaseEntity 类。我想提供一种方法,以某种方式连接到此类的后代中引入的新属性。我在想的是:
public class MyEntity : BaseEntity
{
[DataElement]
public int NewProperty { get; set; }
}
如果我可以编写一个属性 DataElement
来 Hook getter 和 setter,那么我的 API 将在访问时知道该属性。
这可能吗?
UPD:我将尝试解释它的来源。我有这个 BaseEntity 本身没有任何数据。它的后代将声明它们可能持有哪些数据作为属性。我希望能够遍历对象拥有的所有数据(以非常特定的形式将其存储在数据库中)。一种方法是反射(reflection)。但我考虑过通过属性来实现,这些属性会在访问属性时注册数据。
最佳答案
当然,它看起来类似于以下内容:
[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
}
}
}
然而,将 Logic 注入(inject) setter 是一项不同的任务,需要在编译后完成:Why is post-compilation code injection a better idea than pre-compilation code injection?
注入(inject) MSIL 并不容易。看看这个示例代码: http://www.codeproject.com/Articles/37549/CLR-Injection-Runtime-Method-Replacer
关于c# - 创建挂接到属性的 getter 和 setter 的 C# 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21906742/