简体   繁体   English

使用 Attributes 向属性的 set/get 方法添加装饰代码

[英]Use Attributes to add decoration code to property's set/get method

I don't know if I am asking the impossible or not, I have tried to see what I could find via Google but perhaps I am not expressing what I am looking for in the right search terms.我不知道我是否在问不可能的事情,我试图通过谷歌看看我能找到什么,但也许我没有用正确的搜索词表达我正在寻找的东西。 If it is out there please forgive me!如果在那里,请原谅我!

I was hoping to use a Custom Attribute to execute additional code when the set method of a property is executed.我希望在执行属性的 set 方法时使用自定义属性来执行附加代码。

Here is some pseudo code:下面是一些伪代码:

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

}

Rarely is something as simple as pseudo code so I am prepared to do a bit of work, I just need some direction if I could please :)很少有像伪代码这样简单的东西,所以我准备做一些工作,如果可以的话,我只需要一些指导:)

Thank you!谢谢!

Attribute s are not suitable for this manner,they just add meta information on your members and you can read them via Reflection . Attribute不适合这种方式,它们只是在您的成员上添加元信息,您可以通过Reflection读取它们。 Instead you can use some thing like Castle.Proxy to have interceptor on your methods and properties.相反,您可以使用诸如Castle.Proxy东西在您的方法和属性上使用拦截器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在属性的Set {}方法中获取属性名称 - Get property name in the property's Set{} method 服务未实现Property的get / set方法 - Service doesn't implement Property's get/set method 装饰在ViewModel属性上使用不同的名称进行绑定 - Decoration on ViewModel property to use a different name for binding 如何获取绑定对象属性的属性? - How to get the attributes of a bound object's property? 如何通过attribute.add属性传递Eval方法? - How to pass an Eval method through the attributes.add property? C#在继承的类中为父级属性添加自定义属性 - C# add custom attributes for a parent's property in an inherited class 将属性添加到覆盖的属性 - Add attributes to overridden property 我可以从自定义JsonConverter的WriteJson方法获取属性的属性吗? - Can I get the attributes on a property from the WriteJson method of a custom JsonConverter? 将代码放在依赖项属性的setter块中是安全的,还是应该总是使用回调方法? - Is it safe to put code in a dependency property's setter block, or should I always use a callback method? 如何保护 List 的 Add 方法,同时使用 get 属性公开 List? - How to make List's Add method protected, while exposing List with get property?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM