foreach (Dictionary<string, object> dictionary in listOfDictionaries)
{
if( object.Equals(dictionary, listOfDictionaries.Last() )
{
//Do something on last iteration of foreach loop.
}
}我很快就意识到我想要一个引用等于,但它仍然提出了这个代码如何不能被击中的问题。object.Equals不是隐式知道如何比较两个字典,从而返回不相等吗?
发布于 2011-06-10 04:45:38
此测试通过。
什么事情没有像你预期的那样发生?
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
const int length = 10;
var j = 0;
List<Dictionary<string, object>> theList = new List<Dictionary<string, object>>();
for (int i = length - 1; i >= 0; i--)
{
var theDictionary = new Dictionary<string, object>();
theDictionary.Add("string-" + i + "-" + j++, new object());
theDictionary.Add("string-" + i + "-" + j++, new object());
theDictionary.Add("string-" + i + "-" + j++, new object());
theDictionary.Add("string-" + i + "-" + j++, new object());
theList.Add(theDictionary);
}
var theTested = new CodeToTest(theList);
var returnedValue = theTested.TestThis();
Assert.AreEqual(returnedValue,length);
}
}
class CodeToTest
{
private List<Dictionary<string, object>> listOfDictionaries;
public CodeToTest(List<Dictionary<string, object>> listOfDictionaries)
{
this.listOfDictionaries = listOfDictionaries;
}
public int TestThis()
{
var i = 0;
foreach (Dictionary<string, object> dictionary in listOfDictionaries)
{
i++;
if (object.Equals(dictionary, listOfDictionaries.Last()))
{
Console.WriteLine("Got here: " + i);
return i;
}
}
return 0;
}
}https://stackoverflow.com/questions/6298869
复制相似问题