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