根据MSDN文档,元组对象等于方法将使用两个元组对象的值。
为什么下列情况不产生同样的结果:
[Test]
public void TestTupleWithDictionary()
{
Dictionary<Tuple<string, string>, string> values = new Dictionary<Tuple<string, string>, string>();
values.Add(new Tuple<string, string>("1", "1"), "Item 1");
values.Add(new Tuple<string, string>("1", "2"), "Item 2");
Assert.IsNotNull(values.FirstOrDefault(x => x.Key == new Tuple<string, string>("1", "2")));
string value;
values.TryGetValue(new Tuple<string, string>("1", "2"), out value);
Assert.IsNotNullOrEmpty(value);
}为什么values.FirstOrDefault(x => x.Key == new Tuple<string, string>("1", "2"))返回null,因为values.TryGetValue(new Tuple<string, string>("1", "2"), out value);找到正确的键并返回值?
发布于 2016-02-03 09:02:13
您使用的是==,它没有重载Tuple<,>,所以它使用的是引用身份检查.当你构建了一个新的元组时,这是不可能的。
这是正确的,但不可取:
// Don't do this!
values.FirstOrDefault(x => new Tuple<string, string>("1", "2").Equals(x.Key))这将:
https://stackoverflow.com/questions/35172431
复制相似问题