【发布时间】:2011-02-17 17:04:19
【问题描述】:
快速询问该社区的见解:哪个更可取?
选项①
// How many spaces are there in the beginning of string? (and remove them)
int spaces = text.Length;
text = text.TrimStart(' ');
spaces -= text.Length;
- 优点:在单独的行上赋值,因此副作用是明确的
-
缺点:第一行本身看起来很荒谬;你必须注意第三行才能理解它
选项②
// How many spaces are there in the beginning of string? (and remove them)
int spaces = text.Length - (text = text.TrimStart(' ')).Length;
- 优点:语句在其执行的计算方面是有意义的
- 缺点: 赋值有点隐藏在表达式中;副作用可以忽略
【问题讨论】:
-
可爱的 Unicode 数字。
-
我更喜欢第一种代码风格,因为第二种很难支持
-
表达式中的赋值(一般的突变)通常[总是]错误(但请参阅
MoveNext)——也就是说,它们使代码更难维护,更难推理。很容易查看第一个示例并选择“我应该使用更好的名称并避免对spaces变量进行突变”。第二个只是令人困惑——有太多的事情需要在心理上进行跟踪。
标签: c# coding-style