【问题标题】:Working around the lack of co/contravariance in IDictionary<TKey, TValue>解决 IDictionary<TKey, TValue> 中缺乏协方差的问题
【发布时间】:2014-12-01 05:19:19
【问题描述】:

我有一个具有如下属性的低级类:

public IDictionary<IHttpParam, IHttpArg> Parameters {get;}

我的一个更高级别的类使用这个类,但也公开了它自己的称为参数的属性,但类型不同:

public IDictionary<CommandParameter, ICommandArgument> Parameters {get;}

CommandParameter 实现了 IHttpParam 接口,而 ICommandArgument 扩展了 IHttpArg 接口,所以理想情况下,我希望能够像这样实现它:

public IDictionary<CommandParameter, ICommandArgument> Parameters { get { return this.httpReq.Parameters; } }

不幸的是,这是不可能的,因为 IDictionary 接口上缺乏协方差。我了解它无法支持此语言功能的技术原因,但解决此问题的最佳方法是什么?

我想一种选择是创建并返回一个包装器IDictionary&lt;TKey, TVal&gt;,它将所有对IDictionary&lt;CommandParameter, ICommandArgument&gt; 的调用转换为对底层IDictionary 的调用。包装器将通过从一个接口到另一个接口的大量转换来实现这一点,我认为这可能会损害性能。有没有更好的解决方案?

谢谢。

【问题讨论】:

    标签: c# .net dictionary casting covariance


    【解决方案1】:

    我会写一些像public ICommandArgument GetParameter(CommandParameter param) 这样的方法,或者以其他一些懒惰的方式实现Parameters 字典,作为一个函数。不幸的是,我看不到任何关于选角的方法,但我认为这里的性能损失不会那么高。您正在处理 HTTP,因此强制转换几乎不会成为瓶颈。

    【讨论】:

    • 相当公平。我希望有一种方法可以透明地传回底层字典,而不会影响性能,但从宏观上看,我认为这不会产生太大影响。
    猜你喜欢
    • 2012-11-15
    • 2012-07-25
    • 2013-04-08
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    相关资源
    最近更新 更多