C# 如何将通过反射获得的方法分配给委托?(或:如何通过反射加快方法调用)

C# 如何将通过反射获得的方法分配给委托?(或:如何通过反射加快方法调用),c#,reflection,delegates,unity3d,invoke,C#,Reflection,Delegates,Unity3d,Invoke,我知道已经有这样的问题了,但我真的不明白答案(我似乎无法对它们发表评论) 我对思考是完全陌生的,对代表们也是相当陌生的,所以这对我来说相当困难 不久前,我使用反射(第一次)获得了一种方法,我这样做(简化): 这是可行的,但问题是它比直接调用方法慢得多。 所以我想,也许我可以以某种方式将它分配给一个委托,然后调用该委托,而不是使用invoke,我认为这样会更快。(是的,对吗?) 但我找不到如何做到这一点。 我不理解msdn上的文档:(我甚至不确定他们的结局是否和我想做的一样), 我也不明白从阅读这

我知道已经有这样的问题了,但我真的不明白答案(我似乎无法对它们发表评论)

我对思考是完全陌生的,对代表们也是相当陌生的,所以这对我来说相当困难

不久前,我使用反射(第一次)获得了一种方法,我这样做(简化):

这是可行的,但问题是它比直接调用方法慢得多。 所以我想,也许我可以以某种方式将它分配给一个委托,然后调用该委托,而不是使用invoke,我认为这样会更快。(是的,对吗?)

但我找不到如何做到这一点。 我不理解msdn上的文档:(我甚至不确定他们的结局是否和我想做的一样), 我也不明白从阅读这篇文章中我必须做什么

(我试过的都没用)

那么,有谁能向我解释一下在我提供的示例代码中我必须做什么吗?

要以“简单”的方式完成这项工作,您需要比
对象更准确地了解目标;i、 e.而不是:

object perlinObj;
您需要:

SomeType perlinObj;
然后,我们使用
Delegate.CreateDelegate
来创建一个委托,而不是存储
MethodInfo
,注意,为了方便起见,我在这里使用
int
来代替
Vector3

Func<SomeType, int, float> PerlinMethod;
//...
PerlinMethod = (Func<SomeType, int, float>) Delegate.CreateDelegate(
        typeof(Func<SomeType, int, float>),
        null,
        type.GetMethod("GetValue", new Type[] { typeof(int) }));
//...
float PerlinFunction(int pos)
{
    return PerlinMethod(perlinObj, pos);
}
Func<SomeType, int, float> PerlinMethod;
//...
PerlinMethod = (Func<SomeType, int, float>) Delegate.CreateDelegate(
        typeof(Func<SomeType, int, float>),
        null,
        type.GetMethod("GetValue", new Type[] { typeof(int) }));
//...
float PerlinFunction(int pos)
{
    return PerlinMethod(perlinObj, pos);
}
Func<int, float> PerlinMethod;
//...
PerlinMethod = (Func<int, float>) Delegate.CreateDelegate(
        typeof(Func<int, float>),
        perlinObj,
        type.GetMethod("GetValue", new Type[] { typeof(int) }));
//...
float PerlinFunction(int pos)
{
    return PerlinMethod(pos);
}
Func<object, int, float> PerlinMethod;
//...
var target = Expression.Parameter(typeof(object));
var arg = Expression.Parameter(typeof(int));
var call = Expression.Call(
    Expression.Convert(target, type),
    type.GetMethod("GetValue", new Type[] { typeof(int) }),
    arg);

PerlinMethod = Expression.Lambda<Func<object,int,float>>(
    call, target, arg).Compile();