在 c# 中用 Reflection 或类似的(无第三方库)替换 Property Getter/Setter
我有一个包含在类中的属性,例如
public class Greeter {
private Hashtable _data;
public string HelloPhrase { get; set; }
public Greeter(data) {
_data = data;
}
}
我想做的就是向 HelloPhrase 属性添加一个属性,如下所示,
[MyCustomAttribute("Hello_Phrase")]
public string SayHello { get; set; }
这样在构造函数期间我可以反映 MyCustomAttribute 所在的类(Greeter)中的属性定义属性的 Get/Set 方法并将其设置为匿名方法/委托。
public Greeter(data) {
_data = data;
ConfigureProperties();
}
我已设法从类中获取 PropertyInfo,但这仅公开 GetSetMethod (http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getsetmethod.aspx) 和相应的 GetGetMethod。
我已经阅读了此处和在线的一些问题,但找不到不使用某种方面库的答案。
任何人都可以提供在运行时设置 Get/Set 方法的指针吗?理想的情况是像这样的代表
x =>_data[keyDefinedByAttribute];
I've got a property contained in a class for example
public class Greeter {
private Hashtable _data;
public string HelloPhrase { get; set; }
public Greeter(data) {
_data = data;
}
}
What I would like to do is add an Attribute to the HelloPhrase property, like this
[MyCustomAttribute("Hello_Phrase")]
public string SayHello { get; set; }
Such that during the constructor I can reflect over the Properties in the Class(Greeter) where MyCustomAttribute has been defined and set the Get/Set methods of the property to an anonymous method / delegate.
public Greeter(data) {
_data = data;
ConfigureProperties();
}
I've managed to get the PropertyInfo's from the class but this only exposes GetSetMethod (http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getsetmethod.aspx) and the corresponding GetGetMethod.
I've read through some of the questions here and online but can't find an answer that doesn't use an Aspects library of some sort.
Could anyone provider pointers to setting the Get/Set methods at runtime? Ideally to a delegate like
x =>_data[keyDefinedByAttribute];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能这样做。您无法动态交换属性 getter 和 setter 的实现。您可以获得的最接近的是:
动态代理可能适合也可能不适合你,但在我看来,我更喜欢使用它而不是方面的解决方案。但是,动态行为将在代理类中表现出来(无论是接口还是通过动态子类化和覆盖虚拟属性)。
但在任何情况下都不存在像
SetGetMethod
或SetSetMethod< 这样的东西。 /代码>。
You can't do this. You cannot dynamically swap out the implementation of property getters and setters. The closest you can get are either:
Dynamic proxies may or may not suit you, but IMO I'd much prefer a solution that uses that over aspects. However, the dynamic behavior will be surfaced in a proxy class (either of an interface or by dynamically subclassing and overriding your virtual properties.)
But under no circumstance is there anything like
SetGetMethod
orSetSetMethod
.