为任何方法创建Func或Action(在c#中使用反射)

前端之家收集整理的这篇文章主要介绍了为任何方法创建Func或Action(在c#中使用反射)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的应用程序基于设置动态加载dll
数据库(文件,类和方法名称).为了方便,加快和减少使用反射我想要一个缓存….

遵循使用:

  1. MethodInfo.Invoke

没有什么表现(Reflection Performance – Create Delegate (Properties C#))
我想翻译任何对方法调用.我想到了会这样工作的东西:

  1. public static T Create<T>(Type type,string methodName) // or
  2. public static T Create<T>(MethodInfo info) // to use like this:
  3. var action = Create<Action<object>>(typeof(Foo),"AnySetValue");

一个要求是所有的参数,可以是对象.

我正在试图处理表达,到目前为止我有这样的事情:

  1. private void Sample()
  2. {
  3. var assembly = Assembly.GetAssembly(typeof(Foo));
  4.  
  5. Type customType = assembly.GetType("Foo");
  6.  
  7. var actionMethodInfo = customType.GetMethod("AnyMethod");
  8. var funcMethodInfo = customType.GetMethod("AnyGetString");
  9. var otherActionMethod = customType.GetMethod("AnySetValue");
  10. var otherFuncMethodInfo = customType.GetMethod("OtherGetString");
  11.  
  12. var foo = Activator.CreateInstance(customType);
  13. var actionAccessor = (Action<object>)BuildSimpleAction(actionMethodInfo);
  14. actionAccessor(foo);
  15.  
  16. var otherAction = (Action<object,object>)BuildOtherAction(otherActionMethod);
  17. otherAction(foo,string.Empty);
  18.  
  19. var otherFuncAccessor = (Func<object,object>)BuildFuncAccessor(funcMethodInfo);
  20. otherFuncAccessor(foo);
  21.  
  22. var funcAccessor = (Func<object,object,object>)BuildOtherFuncAccessor(otherFuncMethodInfo);
  23. funcAccessor(foo,string.Empty);
  24. }
  25.  
  26. static Action<object> BuildSimpleAction(MethodInfo method)
  27. {
  28. var obj = Expression.Parameter(typeof(object),"o");
  29.  
  30. Expression<Action<object>> expr =
  31. Expression.Lambda<Action<object>>(
  32. Expression.Call(
  33. Expression.Convert(obj,method.DeclaringType),method),obj);
  34.  
  35. return expr.Compile();
  36. }
  37.  
  38. static Func<object,object> BuildFuncAccessor(MethodInfo method)
  39. {
  40. var obj = Expression.Parameter(typeof(object),"o");
  41.  
  42. Expression<Func<object,object>> expr =
  43. Expression.Lambda<Func<object,object>>(
  44. Expression.Convert(
  45. Expression.Call(
  46. Expression.Convert(obj,typeof(object)),obj);
  47.  
  48. return expr.Compile();
  49.  
  50. }
  51.  
  52. static Func<object,object> BuildOtherFuncAccessor(MethodInfo method)
  53. {
  54. var obj = Expression.Parameter(typeof(object),"o");
  55. var value = Expression.Parameter(typeof(object));
  56.  
  57. Expression<Func<object,object>>(
  58. Expression.Call(
  59. Expression.Convert(obj,method,Expression.Convert(value,method.GetParameters()[0].ParameterType)),obj,value);
  60.  
  61. return expr.Compile();
  62.  
  63. }
  64.  
  65. static Action<object,object> BuildOtherAction(MethodInfo method)
  66. {
  67. var obj = Expression.Parameter(typeof(object),"o");
  68. var value = Expression.Parameter(typeof(object));
  69.  
  70. Expression<Action<object,object>> expr =
  71. Expression.Lambda<Action<object,object>>(
  72. Expression.Call(
  73. Expression.Convert(obj,value);
  74.  
  75. return expr.Compile();
  76. }
  1. public class Foo
  2. {
  3. public void AnyMethod() {}
  4.  
  5. public void AnySetValue(string value) {}
  6.  
  7. public string AnyGetString()
  8. { return string.Empty; }
  9.  
  10. public string OtherGetString(string value)
  11. { return string.Empty; }
  12. }

有没有办法简化这段代码? (我相信可以创建一个只使用泛型的方法..)当你有3,4,5,任何参数像我一样?

我在想,如果有这样的话呢?

https://codereview.stackexchange.com/questions/1070/generic-advanced-delegate-createdelegate-using-expression-trees

但是我会有更多的参数(在动作或函数中),这个参数(第一个参数)要执行一个对象.
这可能吗?

解决方法

我已经做了一个满足您所有要求的示例程序(我想!)
  1. class Program
  2. {
  3. class MyType
  4. {
  5. public MyType(int i) { this.Value = i; }
  6.  
  7. public void SetValue(int i) { this.Value = i; }
  8.  
  9. public void SetSumValue(int a,int b) { this.Value = a + b; }
  10.  
  11. public int Value { get; set; }
  12. }
  13.  
  14. public static void Main()
  15. {
  16. Type type = typeof(MyType);
  17.  
  18. var mi = type.GetMethod("SetValue");
  19.  
  20. var obj1 = new MyType(1);
  21. var obj2 = new MyType(2);
  22.  
  23. var action = DelegateBuilder.BuildDelegate<Action<object,int>>(mi);
  24.  
  25. action(obj1,3);
  26. action(obj2,4);
  27.  
  28. Console.WriteLine(obj1.Value);
  29. Console.WriteLine(obj2.Value);
  30.  
  31. // Sample passing a default value for the 2nd param of SetSumValue.
  32. var mi2 = type.GetMethod("SetSumValue");
  33.  
  34. var action2 = DelegateBuilder.BuildDelegate<Action<object,int>>(mi2,10);
  35.  
  36. action2(obj1,3);
  37. action2(obj2,4);
  38.  
  39. Console.WriteLine(obj1.Value);
  40. Console.WriteLine(obj2.Value);
  41.  
  42. // Sample without passing a default value for the 2nd param of SetSumValue.
  43. // It will just use the default int value that is 0.
  44. var action3 = DelegateBuilder.BuildDelegate<Action<object,int>>(mi2);
  45.  
  46. action3(obj1,3);
  47. action3(obj2,4);
  48.  
  49. Console.WriteLine(obj1.Value);
  50. Console.WriteLine(obj2.Value);
  51. }
  52. }

DelegateBuilder类:

  1. public class DelegateBuilder
  2. {
  3. public static T BuildDelegate<T>(MethodInfo method,params object[] missingParamValues)
  4. {
  5. var queueMissingParams = new Queue<object>(missingParamValues);
  6.  
  7. var dgtMi = typeof(T).GetMethod("Invoke");
  8. var dgtRet = dgtMi.ReturnType;
  9. var dgtParams = dgtMi.GetParameters();
  10.  
  11. var paramsOfDelegate = dgtParams
  12. .Select(tp => Expression.Parameter(tp.ParameterType,tp.Name))
  13. .ToArray();
  14.  
  15. var methodParams = method.GetParameters();
  16.  
  17. if (method.IsStatic)
  18. {
  19. var paramsToPass = methodParams
  20. .Select((p,i) => CreateParam(paramsOfDelegate,i,p,queueMissingParams))
  21. .ToArray();
  22.  
  23. var expr = Expression.Lambda<T>(
  24. Expression.Call(method,paramsToPass),paramsOfDelegate);
  25.  
  26. return expr.Compile();
  27. }
  28. else
  29. {
  30. var paramThis = Expression.Convert(paramsOfDelegate[0],method.DeclaringType);
  31.  
  32. var paramsToPass = methodParams
  33. .Select((p,i + 1,queueMissingParams))
  34. .ToArray();
  35.  
  36. var expr = Expression.Lambda<T>(
  37. Expression.Call(paramThis,paramsOfDelegate);
  38.  
  39. return expr.Compile();
  40. }
  41. }
  42.  
  43. private static Expression CreateParam(ParameterExpression[] paramsOfDelegate,int i,ParameterInfo callParamType,Queue<object> queueMissingParams)
  44. {
  45. if (i < paramsOfDelegate.Length)
  46. return Expression.Convert(paramsOfDelegate[i],callParamType.ParameterType);
  47.  
  48. if (queueMissingParams.Count > 0)
  49. return Expression.Constant(queueMissingParams.Dequeue());
  50.  
  51. if (callParamType.ParameterType.IsValueType)
  52. return Expression.Constant(Activator.CreateInstance(callParamType.ParameterType));
  53.  
  54. return Expression.Constant(null);
  55. }
  56. }

怎么运行的

核心是BuildDelegate方法

static T BuildDelegate< T>(MethodInfo方法)

> T是要创建的委托类型.
方法是要由生成的委托调用方法的MethodInfo.

示例调用:var action = BuildDelegate< Action< object,int>>(mi);

参数规则:

>如果传递的方法是一个实例方法,生成的委托的第一个参数将接受包含方法本身的对象的实例.所有其他参数将被传递给该方法.>如果传递的方法是一个静态方法,那么生成的委托的所有参数将被传递给该方法.>缺少参数将传递默认值.>额外的参数将被丢弃.

猜你在找的C#相关文章