8

我刚刚有一个单元测试失败,原因很奇怪,涉及IDictionary<object, object>.

IDictionary<K,V>有两种Remove方法。一个拿一个K,另一个拿一个KeyValuePair<K,V>。考虑这两个彼此非常相似但行为不完全相同的字典:

IDictionary<string, object> d1 = new Dictionary<string, object>();
IDictionary<object, object> d2 = new Dictionary<object, object>();
d1.Add("1", 2);
d2.Add("1", 2);
Console.WriteLine(d1.Remove(new KeyValuePair<string, object>("1", 2)));
Console.WriteLine(d2.Remove(new KeyValuePair<object, object>("1", 2)));

输出为True,则False。既然KeyValuePair<object,object>是 所期望的确切类型d2.Remove(KeyValuePair<object,object>),为什么编译器会调用d2.Remove(object)呢?

验尸说明:

在提示我问题的场景中,我没有IDictionary<object,object>直接使用,而是通过通用参数:

public class DictionaryTests<DictT> where DictT :
    IDictionary<object,object>, new()

因为问题是IDictionary优先于ICollection我决定通过包含ICollection在约束列表中来“解决问题”:

public class DictionaryTests<DictT> where DictT :
    ICollection<KeyValuePair<object, object>>, IDictionary<object,object>, new()

但这并没有改变编译器的想法......我想知道为什么不。)

4

1 回答 1

2

为问题提供解决方案(也请参阅评论):

Console.WriteLine( 
   ((ICollection<KeyValuePair<object, object>) d2).
      Remove(new KeyValuePair<object, object>("1", 2)));
于 2013-04-11T07:33:12.337 回答