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


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01