我正在尝试为通用接口方法创建一个 开放实例委托,但我不断收到 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?
微软已经回答,CLR 无法做到这一点是一个已知问题,但在当前版本的 .网.正如我在那儿解释的那样,为什么这仍然是不可能的.出于某种原因,开放委托不能重用 CLR 中其他地方使用的调度逻辑,这对我来说似乎很奇怪.
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.
这篇关于通用接口方法的开放委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!