C# 中的保留关键字是什么?

csharpprogrammingserver side programming更新于 2025/10/15 18:07:17

关键字是 C# 编译器预定义的保留字。这些关键字不能用作标识符。如果要使用这些关键字作为标识符,可以在关键字前加上 @ 字符。

在 C# 中,某些标识符在代码上下文中具有特殊含义,例如 get 和 set,它们被称为上下文关键字。

下表列出了保留关键字 −

abstractAsbaseboolbreakbytecase
catchCharcheckedclassconstcontinuedecimal
defaultdelegatedodoubleelseenumevent
explicitExternfalsefinallyfixedfloatfor
foreachGotoifimplicitinin (generic modifier)int
interfaceinternalislocklongnamespacenew
nullObjectoperatoroutout (generic modifier)overrideparams
privateprotectedpublicreadonlyrefreturnsbyte
sealedShortsizeofstackallocstaticstringstruct
switchThisthrowtruetrytypeofuint
ulonguncheckedunsafeushortusingvirtualvoid
volatileWhile

让我们看一个在 C# 中使用 bool 保留关键字的示例 −

示例

using System;
using System.Collections;

class Demo {
   static void Main() {
      bool[] arr = new bool[5];
      arr[0] = true;
      arr[1] = true;
      arr[2] = false;
      arr[3] = false;

      BitArray bArr = new BitArray(arr);

      foreach (bool b in bArr) {
         Console.WriteLine(b);
      }

      bool str = arr[1];
      Console.WriteLine("Value of 2nd element:"+str);
   }
}

输出

True
True
False
False
False
Value of 2nd element:True

相关文章