在C#
中,当调用Count或Length个属性时,C#
是否在内部跟踪集合更新时的计数?或者,它是否在每次调用这些属性时计算下划线元素?
我在试着了解下面两个代码中哪一个更好
if(collection.Count > 0)
{
if(collection.Count > 5)
{
// more than 5
} else if(collection.Count > 10 && collection.Count <= 15)
{
// more than 10
} else {
// more than 15
}
}
else
{
// collection is empty
}
或者我应该这样做
var count = collection.Count;
if(count > 0)
{
if(count > 5)
{
// more than 5
} else if(count > 10 && count <= 15)
{
// more than 10
} else {
// more than 15
}
}
else
{
// collection is empty
}