C# 编码规范与语言技巧

整理 C# 编码规范、扩展方法、泛型实例化、命名参数等语言技巧。

1. 标识符规则

  • 尽管可以包含数字字符,但它们必须以字母或下划线开头。
  • 不能把 C# 关键字用作标识符。如果需要把某一保留字用作标识符,可以在标识符前加上前缀符号 @,告知编译器其后的内容是一个标识符。例如:abstract 是 C# 关键字,@abstract 是有效标识符。

2. 命名约定

2.1 Pascal 大小写形式

  • 名称空间和类,以及基类中的成员等名称,如:EmployeeSalary
  • 在 C# 中常量(其他语言中常常全部大写)的名称,如:const int MaximumLength;

2.2 camel 大小写形式

  • 类型中所有私有成员字段的名称,如:private int _subscriberId; 注意前缀名常常用一条下划线开头。
  • 传递给方法的所有参数的名称,如:public void RecordSale(string salesmanName, int quantity);

3. 名称空间的名称

Microsoft 建议使用如下名称空间:<CompanyName>.<TechnologyName>。

4. 属性和方法的使用

满足以下所有条件时,应把它设置为属性,否则应使用方法:

  • 客户端代码应能读取它的值,最好不要使用只写属性。
  • 读取该值不应花太长的时间。
  • 读取该值不应有任何细微的和不希望的负面效应。
  • 可以按照任何顺序设置属性。
  • 顺序读取属性也应有相同的效果。

5. 字段的用法

字段应总是私有的,但在某些情况下也可以把常量或只读字段设置为公有。原因是如果把字段设置为公有,就不利于以后扩展或修改类。

6. 扩展方法

扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。仅当你使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。

namespace CustomExtensions
{
    // Extension methods must be defined in a static class
    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}

namespace Extension_Methods_Simple
{
    // Import the extension method namespace.
    using CustomExtensions;

    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            // Call the method as if it were an
            // instance method on the type. Note that the first
            // parameter is not specified by the calling code.
            int i = s.WordCount();
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}

7. 实例化泛型对象

方法 1:

void Method<T>(T t) where T : new()
{
    T tmp = new T();
}

方法 2:

void Method<T>(T t)
{
    T tmp = Activator.CreateInstance<T>();
}

8. 限定泛型参数的超类

// U 是 CLASSA 类或是其子类
// V 是 CLASSB 类或是其子类
void Method<U, V>(U u, V v) where U : CLASSA where V : CLASSB
{
}

9. using 关键字的两种用途

  • 引用名称空间,如:using System;
  • 给类和名称空间指定别名。如果名称空间的名称非常长,又要在代码中多次引用,但不希望该名称空间的名称包含在 using 指令中(例如,避免类名冲突),就可以给该名称空间指定一个别名,其语法如下:
using alias = NamespaceName;

10. 方法的命名参数

参数一般需要按定义的顺序传递给方法。命名参数允许按任意顺序传递。如下方法:

string FullName(string firstName, string lastName)
{
    return firstName + " " + lastName;
}

下面的方法调用会返回相同的全名:

FullName("John", "Doe");
FullName(lastName: "Doe", firstName: "John");

❤️ 如果这篇文章对你有帮助,欢迎赞助支持我继续维护 ❤️

☕ Support me ⚡ 爱发电赞助