【问题标题】:Use Attributes to add decoration code to property's set/get method使用 Attributes 将装饰代码添加到属性的 set/get 方法
【发布时间】:2025-12-02 08:40:01
【问题描述】:

我不知道我是否在问不可能的事情,我试图通过 Google 来查看我能找到什么,但也许我没有用正确的搜索词表达我在寻找什么。如果它在那里,请原谅我!

我希望在执行属性的 set 方法时使用自定义属性来执行附加代码。

这是一些伪代码:

public class MyAttribute : System.Attribute{
     AttributedProperty.Get(Property p){
          Console.WriteLine("The value of the Property '{0}' has just been retrieved!", p.Name);
     }
     AttributedProperty.Set(Property p){
          Console.WriteLine("The value of the Property '{0}' has just been set!", p.Name);
     }
}

public class MyClass{
     private string _someProperty;
     [MyAttribute]
     public string SomeProperty{
           get{ return _someProperty;}
           set{ someProperty = value;}
     }

}

很少有像伪代码这样简单的东西,所以我准备做一些工作,如果可以的话,我只需要一些指导:)

谢谢!

【问题讨论】:

    标签: c# properties attributes


    【解决方案1】:

    Attributes 不适合这种方式,他们只是在您的成员上添加元信息,您可以通过Reflection 阅读它们。 相反,您可以使用 Castle.Proxy 之类的东西在您的方法和属性上设置拦截器。

    【讨论】:

    • 感谢您的帮助,Castle.Proxy 看起来非常强大。非常感谢!