打开代理通用接口方法 [英] Open delegate for generic interface method
问题描述
我正在尝试为通用接口方法创建一个开放实例代理,但我不断收到NotSupportedException。以下是不能运行的简化代码:
I'm trying to create an open instance delegate for a generic interface method, but I keep receiving a NotSupportedException. Here is the simplified code that won't run:
interface IFoo
{
void Bar<T>(T j);
}
class Foo : IFoo
{
public void Bar<T>(T j)
{
}
}
static void Main(string[] args)
{
var bar = typeof(IFoo).GetMethod("Bar").MakeGenericMethod(typeof(int));
var x = Delegate.CreateDelegate(typeof(Action<IFoo, int>), null, bar);
}
最后一行抛出NotSupportedException,不支持指定的方法。相比之下,非泛型的开放实例代理运行正常:
The last line throws NotSupportedException, "Specified method is not supported". By comparison, a non-generic open instance delegate runs fine:
interface IFoo
{
void Bar(int j);
}
class Foo : IFoo
{
public void Bar(int j)
{
}
}
static void Main(string[] args)
{
var bar = typeof(IFoo).GetMethod("Bar");
var x = Delegate.CreateDelegate(typeof(Action<IFoo, int>), null, bar);
}
一个封闭的泛型委托也可以工作:
And a closed generic delegate also works:
interface IFoo
{
void Bar<T>(T j);
}
class Foo : IFoo
{
public void Bar<T>(T j)
{
}
}
static void Main(string[] args)
{
var bar = typeof(IFoo).GetMethod("Bar").MakeGenericMethod(typeof(int));
var x = Delegate.CreateDelegate(typeof(Action<int>), new Foo(), bar);
}
所以关闭通用代理和开放实例代理的配方单独工作,但不是合并时。它开始看起来像运行时错误或故意遗漏。任何人都有任何见解?
So the recipe for closed generic delegates and open instance delegates work separately, but not when combined. It's starting to look like either a runtime bug, or intentional omission. Anyone have any insight here?
推荐答案
Microsoft has answered that it's a known problem that the CLR can't do this, but it can't be solved in the current version of .NET. It's still not at all clear why this isn't possible as I explain there. Open delegates must not reuse the dispatching logic used everywhere else in the CLR for some reason, which just seems bizarre to me.
这篇关于打开代理通用接口方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!