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?
推荐答案
微软已经回答,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.
这篇关于通用接口方法的开放委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通用接口方法的开放委托


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01