打开代理通用接口方法 [英] Open delegate for generic interface method

查看:99
本文介绍了打开代理通用接口方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为通用接口方法创建一个开放实例代理,但我不断收到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已经回答说,这是一个已知的问题,CLR无法做到这一点,但在当前版本的.NET中无法解决。现在还不清楚为什么这是不可能的,因为我在这里解释。由于某种原因,开放式代表不能重用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.

这篇关于打开代理通用接口方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆