C# Lambda in MethodInfo invocation

本文关键字:invocation MethodInfo in Lambda | 更新日期: 2023-09-27 18:34:16

我想动态调用lambda表达式,但我得到的只是方法信息。

像这样:

Magic.RegisterStaticPacketHandler<TestPacket>((a, b) => { /* Do Stuff */ });
Magic class:
public void RegisterStaticPacketHandler<T>(PacketReceivedHandler<T> handler) where T : Packet
{
            //Remember the handler with: handler.GetMethodInfo()
}

稍后我想调用此方法。因为 PacketReceivedHandler 是一个委托,所以我可以从中获取"MethodInfo"。如果我调用这个方法信息只是:

methodInfo.Invoke(obj, new object[] { packet, this });

我收到一个异常,给定的对象 (obj) 不适合。设置绑定标志,如"非公共 |实例 |静态"也无济于事。

更新

PacketReceivedHandler 如下所示:

public delegate void PacketReceivedHandler<T>(T packet, Connection connection) where T : Packet;

我把它保存在我的万智牌课上:

private Dictionary<int, Tuple<MethodInfo, object>> id_methodInfo_object = new Dictionary<int, Tuple<MethodInfo, object>>();
  • 方法信息 = 委托
  • object = 委托来自何处
  • id = 用于网络内容的 UID

C# Lambda in MethodInfo invocation

除了

方法之外,您还必须保存委托的Target。最简单的方法是直接存储整个委托本身而不是MethodInfo。像这样:

// Store any lambda or action or anything in their baseclass "Delegate":
Delegate act = new Action<int, int>((a, b) => Console.WriteLine(a + b));
// Dynamically invoke like this:
act.Method.Invoke(act.Target, new object[] {4, 9});

完整示例:

class Program
{
    private static List<Delegate> handlers = new List<Delegate>();
    public static void RegisterHandler<T>(Action<T> del)
    {
        handlers.Add(del);
    }
    public static void InvokeHandlers(params object[] args)
    {
        foreach (var h in handlers)
        {
            h.Method.Invoke(h.Target, args);
        }
    }
    static void Main(string[] args)
    {
        RegisterHandler((object a) => Console.WriteLine("#1:" + a));
        RegisterHandler((object a) => Console.WriteLine("#2:" + a));
        InvokeHandlers("foo");
        InvokeHandlers(1234);
    }
}
public void RegisterStaticPacketHandler<T>(PacketReceivedHandler<T> handler) where T : Packet
{
     _methodInfo = handler.Method;
}

请参阅MSDN 中的详细信息