解析C#编程的通用结构和程序书写格式规范

2019-12-26 16:58:21于海丽
  • 每行只写一条语句。
  • 每行只写一个声明。
  • 如果连续行未自动缩进,请将它们缩进一个制表符位(四个空格)。
  • 在方法定义与属性定义之间添加至少一个空白行。

    使用括号突出表达式中的子句,如下面的代码所示。

    
    if ((val1 > val2) && (val1 > val3))
    {
      // Take appropriate action.
    }
    

    注释约定
    将注释放在单独的行上,而非代码行的末尾。
    以大写字母开始注释文本。
    以句点结束注释文本。
    在注释分隔符 (//) 与注释文本之间插入一个空格,如下面的示例所示。

    
    // The following declaration creates a query. It does not run
    // the query.
    

    不要在注释周围创建格式化的星号块。
    语言准则
    以下各节介绍 C# 遵循以准备代码示例和样本的做法。
    String 数据类型
    使用 + 运算符来连接短字符串,如下面的代码所示。

    string displayName = nameList[n].LastName + ", " + nameList[n].FirstName;
    若要在循环中追加字符串,尤其是在使用大量文本时,请使用 StringBuilder 对象。

    
    var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
    var manyPhrases = new StringBuilder();
    for (var i = 0; i < 10000; i++)
    {
      manyPhrases.Append(phrase);
    }
    //Console.WriteLine("tra" + manyPhrases);
    

    隐式类型的局部变量
    当变量类型明显来自赋值的右侧时,或者当精度类型不重要时,请对本地变量进行隐式类型化。

    
    // When the type of a variable is clear from the context, use var 
    // in the declaration.
    var var1 = "This is clearly a string.";
    var var2 = 27;
    var var3 = Convert.ToInt32(Console.ReadLine());
    

    当类型并非明显来自赋值的右侧时,请勿使用 var。

    
    // When the type of a variable is not clear from the context, use an
    // explicit type.
    int var4 = ExampleClass.ResultSoFar();
    

    请勿依靠变量名称来指定变量的类型。它可能不正确。

    
    // Naming the following variable inputInt is misleading. 
    // It is a string.
    var inputInt = Console.ReadLine();
    Console.WriteLine(inputInt);