小编Mik*_*ler的帖子

在c#中用反射或类似的(没有第三方库)替换Property Getter/Setter

例如,我有一个包含在类中的属性

public class Greeter {
   private Hashtable _data;
   public string HelloPhrase { get; set; }

   public Greeter(data) {
      _data = data;
   }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是向HelloPhrase属性添加一个属性,就像这样

[MyCustomAttribute("Hello_Phrase")]
public string SayHello { get; set; }
Run Code Online (Sandbox Code Playgroud)

这样在构造函数中我可以反映已经定义了MyCustomAttribute的类(Greeter)中的Properties,并将属性的Get/Set方法设置为匿名方法/委托.

  public Greeter(data) {
      _data = data;
      ConfigureProperties();
   }
Run Code Online (Sandbox Code Playgroud)

我已经设法从类中获取PropertyInfo,但这只暴露了GetSetMethod(http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getsetmethod.aspx)和相应的GetGetMethod.

我已经在这里和网上阅读了一些问题,但找不到不使用某种Aspects库的答案.

任何人都可以提供指向在运行时设置Get/Set方法的指针吗?理想情况下,像一个代表

x =>_data[keyDefinedByAttribute]; 
Run Code Online (Sandbox Code Playgroud)

c# reflection properties anonymous-methods aspects

6
推荐指数
1
解决办法
2005
查看次数

标签 统计

anonymous-methods ×1

aspects ×1

c# ×1

properties ×1

reflection ×1