我可以用JS或PHP做到这一点:
while(var input = inputs.pop()) {
// do some bad things with input
}
我在C#上尝试相同,但失败了:
Stack<double[]> localInputs = new Stack<double[]>();
for (int i = 0; i < inputs.Length; i++)
{
localInputs.Push(inputs[i]);
}
while (input = localInputs.Pop()) // this cause error about converting double to bool
{
// do some bad things on c#
}
我该怎么做?为什么我不能这样做?Assign应该返回布尔值,不是吗?
没有。赋值的结果是分配的值,而不是布尔值(好吧,除非您要进行布尔值赋值。但是即使那样,它也与赋值是否成功无关)。换句话说,Assignment:的值var x = someStack.Pop()
是分配给的对象x
。因此,您无法执行此操作的原因是,您分配给布尔类型的类型没有隐式转换(即使存在,也不会意味着您想要的含义)。
例如:
var tmp = "Hello";
Console.WriteLine(tmp = "Goodbye"); // Write the output of an assignment to Console
// Note that the result of the assignment is 'Goodbye', not 'true'
另外,请注意,尝试.Pop()
清空堆栈会抛出InvalidOperationException
,这也不是您想要的while
条件。
相反,您需要使用该.Count
属性来确定是否有任何对象要弹出,然后在while循环内进行弹出。
while (localInputs.Count > 0)
{
var input = localInputs.Pop();
// do some bad things on c#
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句