How can I create an open Delegate from a struct's instance method?

后端 未结 3 1685
鱼传尺愫
鱼传尺愫 2020-12-03 23:44

I have a struct with a private method that I\'d like to invoke. Since I plan to do this in a performance critical section, I\'d like to cache a delegate to perform the actio

3条回答
  •  时光取名叫无心
    2020-12-04 00:10

    You're using this overload of CreateDelegate:

    Creates a delegate of the specified type to represent the specified static method.

    SomeMethod is not a static method.

    Use an overload that allows to specify a target object:

    A target = new A();
    
    Func f = (Func)Delegate.CreateDelegate(
        typeof(Func),
        target,
        typeof(A).GetMethod(
            "SomeMethod",
            BindingFlags.Instance | BindingFlags.NonPublic));
    

    This means you need to create a delegate for each instance of A though. You cannot reuse the same delegate for different instances.

    The best solution is probably to construct a Lambda Expression using LINQ Expression Trees:

    var p = Expression.Parameter(typeof(A), "arg");
    var lambda = Expression.Lambda>(
        Expression.Call(
            p,
            typeof(A).GetMethod(
                "SomeMethod",
                BindingFlags.Instance | BindingFlags.NonPublic)),
        p);
    
    Func f = lambda.Compile();
    

提交回复
热议问题