【发布时间】:2013-05-03 17:04:24
【问题描述】:
我需要一个方法,它接受一个 MethodInfo 实例,该实例表示一个具有任意签名的非泛型静态方法,并返回一个绑定到该方法的委托,该方法以后可以使用 Delegate.DynamicInvoke 方法调用。我的第一次天真的尝试是这样的:
using System;
using System.Reflection;
class Program
{
static void Main()
{
var method = CreateDelegate(typeof (Console).GetMethod("WriteLine", new[] {typeof (string)}));
method.DynamicInvoke("Hello world");
}
static Delegate CreateDelegate(MethodInfo method)
{
if (method == null)
{
throw new ArgumentNullException("method");
}
if (!method.IsStatic)
{
throw new ArgumentNullException("method", "The provided method is not static.");
}
if (method.ContainsGenericParameters)
{
throw new ArgumentException("The provided method contains unassigned generic type parameters.");
}
return method.CreateDelegate(typeof(Delegate)); // This does not work: System.ArgumentException: Type must derive from Delegate.
}
}
我希望MethodInfo.CreateDelegate 方法本身可以找出正确的委托类型。好吧,显然它不能。那么,如何创建一个System.Type 的实例来代表一个具有与提供的MethodInfo 实例匹配的签名的委托?
【问题讨论】:
-
为什么要创建Delegate并使用DynamicInvoke?使用 DynamicInvoke 比 MethodInfo.Invoke 慢很多。
-
@nawfal 不。重复要求可以在您提到的问题中回答此处提出的问题。当表示方法签名的类型未知时,提问者希望能够使用
MethodInfo.CreateDelegate()。在另一个问题中,这已经知道是MyDelegate,因此对这个提问者的问题没有帮助。 -
到底是谁在删除我的 cmets?不是第一次!抱歉@einsteinsci 我找不到我在这里发布的重复帖子,所以我无法检查。如果您能发帖,我将不胜感激。
-
OK 从谷歌缓存中找到它:webcache.googleusercontent.com/…。你是对的,它们不一样。标题让我很困惑。
标签: c# .net reflection delegates methodinfo