C# 编程语言

精选 C# 编程语言 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。

#入门指南

#Hello.cs 示例 示例 示例 示例 示例 示例 示例 示例

class Hello {
  // main method
  static void Main(string[] args)
  {
    // Output: Hello, world!
    Console.WriteLine("Hello, world!");
  }
}

为新的控制台应用创建项目目录

$ dotnet new console

列出所有应用模板

$ dotnet new list

编译并运行 (make sure you are in the project directory)

$ dotnet run
Hello, world!

#变量声明 (Variables)

int intNum = 9;
long longNum = 9999999;
float floatNum = 9.99F;
double doubleNum = 99.999;
decimal decimalNum = 99.9999M;
char letter = 'D';
bool @bool = true;
string site = "qr.warpnav.com";

var num = 999;
var str = "999";
var bo = false;

#基础数据类型 (Primitive Data Types)

Data Type Size Range
int 4 bytes -231 to 231-1
long 8 bytes -263 to 263-1
float 4 bytes 6 to 7 decimal digits
double 8 bytes 15 decimal digits
decimal 16 bytes 28 to 29 decimal digits
char 2 bytes 0 to 65535
bool 1 bit true / false
string 2 bytes per char N/A

#代码注释 (Comments)

// Single-line comment

/* Multi-line
   comment */

// TODO: Adds comment to a task list in Visual Studio

/// Single-line comment used for documentation

/** Multi-line comment
    used for documentation **/

foreach(int num in numbers) {
  Console.WriteLine(num);
}

#C# 字符串深入详解 (C# Strings)

#字符串加号拼接 (String Concatenation)

string first = "John";
string last = "Doe";

string name = first + " " + last;
Console.WriteLine(name); // => John Doe

#字符串插值 (String Interpolation)

string first = "John";
string last = "Doe";

string name = $"{first} {last}";
Console.WriteLine(name); // => John Doe

#字符串常用成员与方法 (String Members)

成员名称 详细说明与功能
Length 返回字符串字符长度的只读属性。
Compare() 比较两个字符串相对顺序的静态方法。
Contains() 判断字符串中是否包含指定的子字符串。
Equals() 判断两个字符串是否具有完全相同的字符数据内容。
Format() 通过 {0} 占位符语法及其他原语对字符串进行格式化拼接。
Trim() 移除字符串首尾的指定字符,默认移除首尾的所有空格。
Split() 根据指定的分隔符拆分字符串,并返回拆分后的子字符串数组。

#原样原义字符串 (Verbatim Strings)

string longString = @"I can type any characters in here !#@$%^&*()__+ '' \n \t except double quotes and I will be taken literally. I even work with multiple lines.";

#成员方法调用示例 (Member Example)

// 使用 System.String 的属性
string lengthOfString = "How long?";
lengthOfString.Length           // => 9

// 使用 System.String 的实例方法
lengthOfString.Contains("How"); // => true

#杂项与概念 (Misc)

#⚙️ .NET 常用核心术语 (.NET Terms)

术语名称 详细定义与解释
运行时 (Runtime) 执行编译后的特定代码单元所必需的辅助服务集合。
公共语言运行时 (CLR) 主要用于定位、加载和管理 .NET 对象。CLR 还负责内存管理、应用宿主托管、线程协调、安全检查及其他底层细节。
托管代码 (Managed Code) 在 .NET 运行时上编译并运行的代码(例如 C#、F#、VB.NET 等)。
非托管代码 (Unmanaged Code) 直接编译为原生机器码、无法直接由 .NET 运行时托管的代码。不包含自动内存管理与垃圾回收机制。C/C++ 编译生成的 DLL 即为典型示例。