使用属性将装饰代码添加到属性';s set/get方法

本文关键字:属性 set 方法 get 添加 代码 | 更新日期: 2023-09-27 17:58:33

我不知道我是否在问不可能的问题,我试图通过谷歌找到什么,但也许我没有用正确的搜索词表达我想要的东西。如果它在外面,请原谅我!

我希望在执行属性的set方法时使用Custom Attribute来执行其他代码。

这里有一些伪代码:

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;}
     }
}

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

谢谢!

使用属性将装饰代码添加到属性';s set/get方法

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