gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:06:14 33 4
gpt4 key购买 nike

我的应用程序根据设置动态加载 dll来自数据库(文件、类和方法名称)。为了促进、加快和减少反射的使用,我想要一个缓存....

遵循使用的想法:

 MethodInfo.Invoke

没有任何表现形式 ( Reflection Performance - Create Delegate (Properties C#) )我想翻译对方法的任何调用。我想到了一些可以像这样工作的东西:

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

一个要求是所有参数都可以是对象。

我正在尝试处理表达式,到目前为止我有这样的东西:

    private void Sample()
{
var assembly = Assembly.GetAssembly(typeof(Foo));

Type customType = assembly.GetType("Foo");

var actionMethodInfo = customType.GetMethod("AnyMethod");
var funcMethodInfo = customType.GetMethod("AnyGetString");
var otherActionMethod = customType.GetMethod("AnySetValue");
var otherFuncMethodInfo = customType.GetMethod("OtherGetString");

var foo = Activator.CreateInstance(customType);
var actionAccessor = (Action<object>)BuildSimpleAction(actionMethodInfo);
actionAccessor(foo);

var otherAction = (Action<object, object>)BuildOtherAction(otherActionMethod);
otherAction(foo, string.Empty);

var otherFuncAccessor = (Func<object, object>)BuildFuncAccessor(funcMethodInfo);
otherFuncAccessor(foo);

var funcAccessor = (Func<object,object,object>)BuildOtherFuncAccessor(otherFuncMethodInfo);
funcAccessor(foo, string.Empty);
}

static Action<object> BuildSimpleAction(MethodInfo method)
{
var obj = Expression.Parameter(typeof(object), "o");

Expression<Action<object>> expr =
Expression.Lambda<Action<object>>(
Expression.Call(
Expression.Convert(obj, method.DeclaringType),
method), obj);

return expr.Compile();
}

static Func<object, object> BuildFuncAccessor(MethodInfo method)
{
var obj = Expression.Parameter(typeof(object), "o");

Expression<Func<object, object>> expr =
Expression.Lambda<Func<object, object>>(
Expression.Convert(
Expression.Call(
Expression.Convert(obj, method.DeclaringType),
method),
typeof(object)),
obj);

return expr.Compile();

}

static Func<object, object, object> BuildOtherFuncAccessor(MethodInfo method)
{
var obj = Expression.Parameter(typeof(object), "o");
var value = Expression.Parameter(typeof(object));

Expression<Func<object, object, object>> expr =
Expression.Lambda<Func<object, object, object>>(
Expression.Call(
Expression.Convert(obj, method.DeclaringType),
method,
Expression.Convert(value, method.GetParameters()[0].ParameterType)),
obj, value);

return expr.Compile();

}

static Action<object, object> BuildOtherAction(MethodInfo method)
{
var obj = Expression.Parameter(typeof(object), "o");
var value = Expression.Parameter(typeof(object));

Expression<Action<object, object>> expr =
Expression.Lambda<Action<object, object>>(
Expression.Call(
Expression.Convert(obj, method.DeclaringType),
method,
Expression.Convert(value, method.GetParameters()[0].ParameterType)),
obj,
value);

return expr.Compile();
}

public class Foo
{
public void AnyMethod() {}

public void AnySetValue(string value) {}

public string AnyGetString()
{ return string.Empty; }

public string OtherGetString(string value)
{ return string.Empty; }
}

有什么办法可以简化这段代码吗? (我相信可以只使用泛型创建一个方法。)当你有 3、4、5 时,任何参数都像我一样?


我在想,如果有这样的事情会怎样:

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

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

最佳答案

我已经制作了一个满足您所有要求的示例程序(我认为!)

class Program
{
class MyType
{
public MyType(int i) { this.Value = i; }

public void SetValue(int i) { this.Value = i; }

public void SetSumValue(int a, int b) { this.Value = a + b; }

public int Value { get; set; }
}

public static void Main()
{
Type type = typeof(MyType);

var mi = type.GetMethod("SetValue");

var obj1 = new MyType(1);
var obj2 = new MyType(2);

var action = DelegateBuilder.BuildDelegate<Action<object, int>>(mi);

action(obj1, 3);
action(obj2, 4);

Console.WriteLine(obj1.Value);
Console.WriteLine(obj2.Value);

// Sample passing a default value for the 2nd param of SetSumValue.
var mi2 = type.GetMethod("SetSumValue");

var action2 = DelegateBuilder.BuildDelegate<Action<object, int>>(mi2, 10);

action2(obj1, 3);
action2(obj2, 4);

Console.WriteLine(obj1.Value);
Console.WriteLine(obj2.Value);

// Sample without passing a default value for the 2nd param of SetSumValue.
// It will just use the default int value that is 0.
var action3 = DelegateBuilder.BuildDelegate<Action<object, int>>(mi2);

action3(obj1, 3);
action3(obj2, 4);

Console.WriteLine(obj1.Value);
Console.WriteLine(obj2.Value);
}
}

DelegateBuilder 类:

public class DelegateBuilder
{
public static T BuildDelegate<T>(MethodInfo method, params object[] missingParamValues)
{
var queueMissingParams = new Queue<object>(missingParamValues);

var dgtMi = typeof(T).GetMethod("Invoke");
var dgtRet = dgtMi.ReturnType;
var dgtParams = dgtMi.GetParameters();

var paramsOfDelegate = dgtParams
.Select(tp => Expression.Parameter(tp.ParameterType, tp.Name))
.ToArray();

var methodParams = method.GetParameters();

if (method.IsStatic)
{
var paramsToPass = methodParams
.Select((p, i) => CreateParam(paramsOfDelegate, i, p, queueMissingParams))
.ToArray();

var expr = Expression.Lambda<T>(
Expression.Call(method, paramsToPass),
paramsOfDelegate);

return expr.Compile();
}
else
{
var paramThis = Expression.Convert(paramsOfDelegate[0], method.DeclaringType);

var paramsToPass = methodParams
.Select((p, i) => CreateParam(paramsOfDelegate, i + 1, p, queueMissingParams))
.ToArray();

var expr = Expression.Lambda<T>(
Expression.Call(paramThis, method, paramsToPass),
paramsOfDelegate);

return expr.Compile();
}
}

private static Expression CreateParam(ParameterExpression[] paramsOfDelegate, int i, ParameterInfo callParamType, Queue<object> queueMissingParams)
{
if (i < paramsOfDelegate.Length)
return Expression.Convert(paramsOfDelegate[i], callParamType.ParameterType);

if (queueMissingParams.Count > 0)
return Expression.Constant(queueMissingParams.Dequeue());

if (callParamType.ParameterType.IsValueType)
return Expression.Constant(Activator.CreateInstance(callParamType.ParameterType));

return Expression.Constant(null);
}
}

工作原理

核心是BuildDelegate方法:

static T BuildDelegate<T>(MethodInfo method)

  • T 是您要创建的委托(delegate)类型。
  • method 是您希望生成的委托(delegate)调用的方法的 MethodInfo。

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

参数规则:

  • 如果传递的方法是实例方法,生成的委托(delegate)的第一个参数将接受包含方法本身的对象实例。所有其他参数都将传递给该方法。

  • 如果传递的方法是静态方法,那么生成的委托(delegate)的所有参数都会传递给该方法。

  • 缺少的参数将传递默认值。

  • 多余的参数将被丢弃。

关于c# - 为任何方法创建 Func 或 Action(在 C# 中使用反射),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041674/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com