Casting a Delegate into an Action or Func in runtime

前端 未结 2 2000
死守一世寂寞
死守一世寂寞 2021-02-14 21:33

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:10

    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(...)
    

提交回复
热议问题