我意识到,一般来说,使用反射会影响性能。(实际上,我本人根本不喜欢反思;这是一个纯粹的学术问题。)
假设存在一些如下所示的类:
public class MyClass {
public string GetName() {
return "My Name";
}
}
在这里忍受我。我知道如果我有一个MyClass被调用的实例x,我可以调用x.GetName()。此外,我可以将Func<string>变量设置为x.GetName.
现在这是我的问题。假设我不知道上面的类被调用MyClass;我有一些对象,x但我不知道它是什么。我可以通过执行以下操作来检查该对象是否具有GetName方法:
MethodInfo getName = x.GetType().GetMethod("GetName");
假设getName不为空。那么我不能进一步检查是否getName.ReturnType == typeof(string)和getName.GetParameters().Length == 0,并且在这一点上,我不是很确定我的getName对象表示的方法肯定可以以Func<string>某种方式强制转换为 a 吗?
我意识到有一个MethodInfo.Invoke,我也意识到我总是可以创建一个Func<string>类似的:
Func<string> getNameFunc = () => getName.Invoke(x, null);
我想我要问的是是否有任何方法可以从一个MethodInfo对象转到它所代表的实际方法,从而在过程中产生反射的性能成本,但在那之后能够直接调用该方法(通过,例如, aFunc<string>或类似的东西)没有性能损失。
我所设想的可能看起来像这样:
// obviously this would throw an exception if GetActualInstanceMethod returned
// something that couldn't be cast to a Func<string>
Func<string> getNameFunc = (Func<string>)getName.GetActualInstanceMethod(x);
(我意识到这不存在;我想知道是否有类似的东西。)