c# - C# 中不允许接口(interface)<动态> - 解决方法

标签 c# generics dynamic interface clr

我有一个正在尝试设计的类,它使用 dynamic作为类型参数:

public class Idea : IEnumerable<dynamic>, IQueryable<dynamic>
{
}

Compiler: Cannot implement a dynamic interface

所以我有这个我不太热衷的解决方法:

public class Idea<T> : IEnumerable<T>, IQueryable<T>
{
}

public class Idea : Idea<dynamic>
{
}

Compiler: success!

我想不出任何其他方法来解决这个问题,而且我不确定是否要公开 Idea<T>给用户。

问题:

  1. 我觉得这里有代码味道......你能确认一下吗?
  2. 为什么 CLR 不允许执行 dynamic接口(interface)?
  3. 有没有我可以使用的模式来实现这一目标而不暴露 Idea<T>

最佳答案

我想回答您最重要的问题“为什么 CLR 不允许实现动态接口(interface)?”

只是因为它没有意义。阅读此 blog post of Chris Burrows这彻底解释了这一点。

例如,覆盖动态成员、匹配签名等时会出现问题

例如这一行说明了很多:

but it’s because when we look at method overrides and overloads, we treat object and dynamic as the same

是的,这是一个问题。该示例在文章中给出:

public class C
{
    public void M(object x) { }
    public void M(dynamic x) { }
}

这确实没有意义,尽管类型似乎不同,但在 CLR 世界中它们并没有。

虽然这似乎是可能的,但根据 CLI 团队的说法,这需要做更多的工作。他们直到现在才发现这对实现很有用:

The metadata team reported that a reading of the CLI spec seemed to indicate that the tables for interface implementations and custom attributes might have permitted it, but anyway no one we know of has ever done this, and it would have been effort expended. We have priorities and a limited budget of time, and this didn’t make the cut.

回答您的其他问题:是的,您是对的,解决方法感觉很糟糕,而且可能确实如此,但它似乎是目前唯一可行的解​​决方案。问问自己是否真的想要和需要这个。如果是,请继续您当前的解决方案。

关于c# - C# 中不允许接口(interface)<动态> - 解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26484096/

相关文章:

c# - 您可以在中间件内部创建 transient DI 服务吗?

c++ - 谁负责删除?

c# - 简单线程问题

c# - 返回初始用户控件后返回 null 的表单

Java 泛型 : Unbounded wildcard is not working with Object type argument

sql-server - SQL Server 在不聚合的情况下透视数据

c# - 如何通过字符串或整数获取枚举值

c# - 为 MVC 3 实现一点 IOC

java - Java中m1和m2泛型方法的区别

c# - 通用对象比较 diff 例程