C#关键字与标识符:规则、完整列表与最佳实践
C#关键字与标识符
掌握C#关键字与标识符基础,它们是定义代码结构与行为的基石。
C#关键字
关键字是C#编译器保留用于自身用途的预定义单词。其含义固定;不可更改,也不能直接用作标识符。
例如:
long mobileNum;
此处long是声明long类型变量mobileNum的关键字。int、char、long等关键字未经修饰不能用作变量名。
尝试将关键字作标识符,如long long;,将导致编译错误。C#包含79个保留关键字,均为小写。完整列表如下:
| abstract | as | base | bool |
| break | byte | case | catch |
| char | checked | class | const |
| continue | decimal | default | delegate |
| do | double | else | enum |
| event | explicit | extern | false |
| finally | fixed | float | for |
| foreach | goto | if | implicit |
| in | in (generic modifier) | int | interface |
| internal | is | lock | long |
| namespace | new | null | object |
| operator | out | out (generic modifier) | override |
| params | private | protected | public |
| readonly | ref | return | sbyte |
| sealed | short | sizeof | stackalloc |
| static | string | struct | switch |
| this | throw | true | try |
| typeof | uint | ulong | unchecked |
| unsafe | ushort | using | using static |
| void | volatile | while |
关键字加@前缀可作标识符:
int @void;
声明一个名为@void的int变量。
上下文关键字
除保留关键字外,C#定义25个上下文关键字。这些词仅在特定上下文有特殊含义,其他场景可作为普通标识符。
| add | alias | ascending |
| async | await | descending |
| dynamic | from | get |
| global | group | into |
| join | let | orderby |
| partial (type) | partial (method) | remove |
| select | set | value |
| var | when (filter condition) | where (generic type constraint) |
| yield |
深入每个关键字请查阅官方文档:C#关键字。
C#标识符
标识符为变量、方法、类等程序元素命名,在作用域内唯一区分各元素。
示例:
int value;
此处value为标识符。未加@前缀使用保留关键字如int break;将触发编译错误。
了解更多变量知识见C#变量。
标识符命名规则
- 不能是C#关键字。
- 必须以字母、下划线(
_)或@符号开头;后续字符可为字母、数字、下划线。 - 不允许空白字符与其他符号(如
$)。 - 标识符区分大小写:getName、GetName、getname互不相同。
合法与非法标识符对比:
| 标识符 | 说明 |
|---|---|
| number | 合法 |
| calculateMarks | 合法 |
| hello$ | 非法(含$) |
| name1 | 合法 |
| @if | 合法(关键字加@) |
| if | 非法(C#关键字) |
| My name | 非法(含空格) |
| _hello_hi | 合法 |
示例:从程序中提取关键字与标识符
以简单Hello World程序为例识别其关键字与标识符。
using System;
namespace HelloWorld
{
class Hello
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
代码片段中的关键字-标识符对应:
| 关键字 | 标识符 |
|---|---|
| using | System |
| namespace | HelloWorld |
| class | Hello |
| static | Main |
| void | args |
| string | Console |
| WriteLine |
字符串字面量"Hello World!"传递给WriteLine。
C语言