5. 声明 5.1 每行的声明数 推荐每行只有一个声明,因为它可以方便注释。int level; // indentation levelint size; // size of table 当声明变量时,不要把多个变量或不同类型的变量放在同一行,例如: int a, b; //What is 'a'? What does 'b' stand for? 上面的例子也显示了变量名不明显的缺陷。当命名变量时要清晰。5.2 初始化 局部变量一旦被声明就要初始化。例如: string name = myObject.Name;或int val = time.Hours; 注意:如果你初始化一个dialog,设计使用using语句: using (OpenFileDialog openFileDialog = new OpenFileDialog()) {...} 5.3 类和接口声明 当编写C#类和接口时,应遵循以下格式化规则: · 在方法名和圆括号“(”开始它的参数列表之间不要使用空格。 · 在声明语句的下一行以大括号"{"标志开始。 · 以"}"结束,通过它自身的缩进与相应的开始标志匹配。 例如: Class MySample : MyClass, IMyInterface{ int myInt; public MySample(int myInt) { this.myInt = myInt ; } void Inc() { ++myInt; } void EmptyMethod() { }} 对于一个大括号的位置参考10.1部分。 6. 语句 6.1 简单语句 每行都应该只包含一条语句。 6.2 返回语句 一个返回语句不要用最外围圆括号。不用: return (n * (n + 1) / 2);用: return n * (n + 1) / 2; 6.3 If, if-else, if else-if else 语句 if, if-else and if else-if else 语句看起来应该像这样: if (condition) {DoSomething();...}if (condition) {DoSomething();...} else {DoSomethingOther();...}if (condition) {DoSomething();...} else if (condition) {DoSomethingOther();...} else {DoSomethingOtherAgain();...} 6.4 for / foreach 语句 一个for语句应该如下形式: for (int i = 0; i < 5; ++i) {...} 或者放置一行(考虑用一个while语句代替)for (initialization; condition; update) ;foreach语句应该像下面所示 :foreach (int i in IntList) {...} 注意:在一个循环中,即使只有一个语句通常也用括弧括起来。 6.5 While/do-while 语句一个while语句应该写成如下形式: while (condition) {...

评论