gpt4 book ai didi

c# - 使用反射创建通用委托(delegate)

转载 作者:可可西里 更新时间:2023-11-01 08:26:38 25 4
gpt4 key购买 nike

我有以下代码:

class Program
{
static void Main(string[] args)
{
new Program().Run();
}

public void Run()
{
// works
Func<IEnumerable<int>> static_delegate = new Func<IEnumerable<int>>(SomeMethod<String>);

MethodInfo mi = this.GetType().GetMethod("SomeMethod").MakeGenericMethod(new Type[] { typeof(String) });
// throws ArgumentException: Error binding to target method
Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), mi);

}

public IEnumerable<int> SomeMethod<T>()
{
return new int[0];
}
}

为什么我不能为我的泛型方法创建委托(delegate)?我知道我可以只使用 mi.Invoke(this, null),但由于我可能要执行 SomeMethod 几百万次,所以我想能够创建一个委托(delegate)并将其缓存为一个小的优化。

最佳答案

你的方法不是静态方法,所以你需要使用:

Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), this, mi);

将“this”传递给第二个参数将允许该方法绑定(bind)到当前对象上的实例方法...

关于c# - 使用反射创建通用委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2419705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com