【发布时间】:2018-07-28 20:53:25
【问题描述】:
在 C# 中,如何使用属性本身或属性作为某种形式反射的标记来注入代码?
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class AddMessage : Attribute
{
public AddMessage()
{
//...
}
}
例如,您可以使用AddMessage 来操作类似这样的自动属性
[AddMessage]
public int Count { get; set; } = 0;
为了看起来像这样的东西?
private int count;
public int Count {
get {
return count;
}
set {
count = value;
Console.WriteLine("Setter Message");
}
}
//Somewhere else
count = 0;
【问题讨论】:
-
你不能用属性来做,但是你可以用AOP来做。您需要类似 OnExit 方面 doc.postsharp.net/t_postsharp_aspects_onmethodboundaryaspect 或 OnSetValue doc.postsharp.net/location-interception
-
@ThomasWeller 感谢您的链接,但由于定价,我很想避免发布尖锐
标签: c# properties attributes aop