C# 表达式和循环之美
这可能相当主观,但是当控制变量在循环中更新时,人们通常如何在 C# 中布置循环控制?我这个学究气的人不喜欢单独的声明和重复。例如。
string line = reader.ReadLine();
while (line != null)
{
//do something with line
line = reader.ReadLine();
}
我的 C 编码员想将其更改为
while (string line = reader.ReadLine() != null)
{
//do something with line
}
,但 C# 的表达式似乎不能那样工作:(
This is probably pretty subjective, but how do people generally lay out their loop control in C# when the control variable is updated in the loop? The pedant in me doesn't like the separate declaration and repetition involved. eg.
string line = reader.ReadLine();
while (line != null)
{
//do something with line
line = reader.ReadLine();
}
The C coder in me wants to change this to
while (string line = reader.ReadLine() != null)
{
//do something with line
}
but C#'s expressions don't seem to work that way :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
选项:
1) 将变量声明为循环,但在条件中对其进行赋值:
2) 使用 for 循环:
3) 创建一个扩展方法,将读取器转换为
IEnumerable
,然后使用:就我个人而言,我喜欢尽可能使用最后一种形式 - 否则我会使用第一种形式。
Options:
1) Declare the variable the loop, but assign it in the condition:
2) Use a for loop instead:
3) Create an extension method to turn a reader into an
IEnumerable<String>
and then use:Personally I like the last one where possible - otherwise I'd use the first form.
您不能在表达式内声明变量。
您可以写
为了更清楚,我更喜欢写
然而,最好的选择是
这将执行等效的操作。
如果您正在读取其他流,则可以创建一个扩展方法,该方法使用以前的语法来启用
foreach
循环。You can't declare a variable inside an expression.
You can write
To make it clearer, I prefer to write
However, the best alternative is
This will perform equivalently.
If you're reading some other stream, you can create an extension method that uses the previous syntax to enable
foreach
loops.就我个人而言,我更喜欢:
尽管总是有 for 结构作为替代:
Personally, I prefer:
There's always the for construct as an alternative though:
我通常会写这样的内容:
I usually write something like:
我同意重复
reader.ReadLine()
表达式不好。一种方法是使用while(true)
和break
:I agree that repeating the
reader.ReadLine()
expression isn't good. One way is to usewhile(true)
andbreak
:怎么样:
然后像这样使用它:
或者你更喜欢:
可以定义为:
How about:
and then use it something like this:
or would you prefer:
that could be defined as: