• C# 编码约定(C# 编程指南)


    原文链接:C# 编码约定(C# 编程指南)   

    英文版:C# Coding Conventions (C# Programming Guide)

    Coding conventions serve the following purposes:

    • They create a consistent look to the code, so that readers can focus on content, not layout.

    • They enable readers to understand the code more quickly by making assumptions based on previous experience.

    • They facilitate copying, changing, and maintaining the code.

    • They demonstrate C# best practices.

    The guidelines in this article are used by Microsoft to develop samples and documentation.

    Naming Conventions

     Qualified names can be broken after a dot (.) if they are too long for a single line, as shown in the following example.

    Layout Conventions

    • Use the default Code Editor settings (smart indenting, four-character indents, tabs saved as spaces). For more information, see Options, Text Editor, C#, Formatting.

    • Write only one statement per line.

    • Write only one declaration per line.

    • If continuation lines are not indented automatically, indent them one tab stop (four spaces).

    • Add at least one blank line between method definitions and property definitions.

    • Use parentheses to make clauses in an expression apparent, as shown in the following code.

    Commenting Conventions

    • Place the comment on a separate line, not at the end of a line of code.

    • Begin comment text with an uppercase letter.

    • End comment text with a period.

    • Insert one space between the comment delimiter (//) and the comment text, as shown in the following example.

    • Do not create formatted blocks of asterisks around comments.

    Language Guidelines

    String Data Type

    • Use string interpolation to concatenate short strings, as shown in the following code.

    • To append strings in loops, especially when you are working with large amounts of text, use a StringBuilder object.

    Implicitly Typed Local Variables

    • Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.

    • Do not use var when the type is not apparent from the right side of the assignment.
    • Do not rely on the variable name to specify the type of the variable. It might not be correct.
    • Avoid the use of var in place of dynamic.
    • Do not use implicit typing to determine the type of the loop variable in foreach loops.

    Unsigned Data Type

    In general, use int rather than unsigned types. The use of int is common throughout C#, and it is easier to interact with other libraries when you use int.

    Use the concise syntax when you initialize arrays on the declaration line.

    Delegates

    Use the concise syntax to create instances of a delegate type.

    try-catch and using Statements in Exception Handling

    • Use a try-catch statement for most exception handling.

    • Simplify your code by using the C# using statement. If you have a try-finally statement in which the only code in the finally block is a call to the Dispose method, use a using statement instead.

    && and || Operators

    To avoid exceptions and increase performance by skipping unnecessary comparisons, use && instead of & and || instead of | when you perform comparisons, as shown in the following example.

    New Operator

    • Use the concise form of object instantiation, with implicit typing, as shown in the following declaration.

    • Use object initializers to simplify object creation.

    Event Handling

    If you are defining an event handler that you do not need to remove later, use a lambda expression.

    public Form2()
    {
        // You can use a lambda expression to define an event handler.
        this.Click += (s, e) =>
            {
                MessageBox.Show(
                    ((MouseEventArgs)e).Location.ToString());
            };
    }
    
    // Using a lambda expression shortens the following traditional definition.
    public Form1()
    {
        this.Click += new EventHandler(Form1_Click);
    }
    
    void Form1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(((MouseEventArgs)e).Location.ToString());
    }
    

      

    Static Members

    Call static members by using the class name: ClassName.StaticMember. This practice makes code more readable by making static access clear. Do not qualify a static member defined in a base class with the name of a derived class. While that code compiles, the code readability is misleading, and the code may break in the future if you add a static member with the same name to the derived class.

    LINQ Queries

    • Use meaningful names for query variables. The following example uses seattleCustomers for customers who are located in Seattle.

    • Use aliases to make sure that property names of anonymous types are correctly capitalized, using Pascal casing.
    • Rename properties when the property names in the result would be ambiguous. For example, if your query returns a customer name and a distributor ID, instead of leaving them as Name and ID in the result, rename them to clarify that Name is the name of a customer, and ID is the ID of a distributor.
    • Use implicit typing in the declaration of query variables and range variables.
    • Align query clauses under the from clause, as shown in the previous examples.
    • Use where clauses before other query clauses to ensure that later query clauses operate on the reduced, filtered set of data.
    • Use multiple from clauses instead of a join clause to access inner collections. For example, a collection of Student objects might each contain a collection of test scores. When the following query is executed, it returns each score that is over 90, along with the last name of the student who received the score.
    var seattleCustomers = from customer in customers
                           where customer.City == "Seattle"
                           select customer.Name;
    
    
    var localDistributors =
        from customer in customers
        join distributor in distributors on customer.City equals distributor.City
        select new { Customer = customer, Distributor = distributor };
    
    
    var localDistributors2 =
        from customer in customers
        join distributor in distributors on customer.City equals distributor.City
        select new { CustomerName = customer.Name, DistributorID = distributor.ID };
    
    var seattleCustomers = from customer in customers
                           where customer.City == "Seattle"
                           select customer.Name;
    
    var seattleCustomers2 = from customer in customers
                            where customer.City == "Seattle"
                            orderby customer.Name
                            select customer;
    
    // Use a compound from to access the inner sequence within each element.
    var scoreQuery = from student in students
                     from score in student.Scores
                     where score > 90
                     select new { Last = student.LastName, score };
    

      

  • 相关阅读:
    【重学计算机】计组D2章:数据表示
    【重学计算机】计组D1章:计算机系统概论
    计算机底层原理杂谈(白话文)
    阿里云安装wordpress遇到的问题
    wordpress数据表结构
    家用计费系统ER图
    java 类中的属性为什么一般都是私有的
    centos 软件库安装
    linux下启动tomcat----Cannot find ./catalina.sh
    jfreechart图表汉字乱码问题解决方案
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/12430116.html
Copyright © 2020-2023  润新知