我可以用JS或PHP做到这一点:
while(var input = inputs.pop()) {
// do some bad things with input
}
Run Code Online (Sandbox Code Playgroud)
我在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#
}
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做?为什么我不能这样做?Assign应该返回boolean,nope?
不.赋值的结果是赋值的值,而不是布尔值(好吧,除非你正在进行布尔赋值.但即便如此,它与赋值是否成功无关).换句话说,赋值的值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'
Run Code Online (Sandbox Code Playgroud)
另外,请注意尝试.Pop()空堆栈会抛出一个InvalidOperationException,这也不是您想要的while条件.
相反,您需要使用该.Count属性来确定是否有任何要弹出的对象,然后在while循环中执行pop.
while (localInputs.Count > 0)
{
var input = localInputs.Pop();
// do some bad things on c#
}
Run Code Online (Sandbox Code Playgroud)