为什么不';这个if语句从来没有被击中过吗
本文关键字:从来没有 语句 这个 if 为什么不 | 更新日期: 2023-09-27 17:58:52
foreach (Dictionary<string, object> dictionary in listOfDictionaries)
{
if( object.Equals(dictionary, listOfDictionaries.Last() )
{
//Do something on last iteration of foreach loop.
}
}
我很快就意识到我想要一个相等的引用,但它仍然提出了一个问题,即如何不能命中此代码。确实反对。Equals不隐含地知道如何比较两个Dictionary,从而返回不相等?
在这种情况下,有几种方法不能命中if
语句的主体。
listOfDictionaries
是一个空集合,因此永远不会测试if
语句listOfDictionaries
可以是生成的序列,其每次迭代都返回Dictionary<string, object>
的新实例,因此元素在迭代之间不具有引用相等性
你能在这里给我们更多的背景信息吗?也许显示listOfDictionaries
的类型?
这里有一个替代解决方案,它不需要像.ToList
那样进行任何额外的分配
using (var e = listOfDictionaries.GetEnumerator()) {
var hasMore = e.MoveNext();
while (hasMore) {
var dictionary = e.Current;
...
hasMore = e.MoveNext();
if (!hasMore) {
// Inside this if block dictionary is the last item in listOfDictionaries
}
}
}
此测试通过。
什么事情没有如你所料?
[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;
}
}