Casting a Delegate into an Action or Func in runtime

前端 未结 2 1187
鱼传尺愫
鱼传尺愫 2021-02-14 21:36

I\'m trying to improve my reflection code by creating Delegates for the Getter and Setter methods.

My code looks like this:

MyO         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-14 22:31

    Is there a reason why you need to use Action or Func to dynamically get/set a propery?

    If not you can use PropertyInfo.GetMethod() and SetMethod()

     MyObject obj = new MyObject();
     PropertyInfo prop = obj.GetType().GetProperty("Prop");
    
     MethodInfo getter = prop.GetMethod();
     getter.Invoke(...)
    
     MethodInfo setter = prop.SetMethod();
     setter.Invoke(...)
    

提交回复
热议问题