如何在 C# 中声明和初始化常量字符串?

csharpprogrammingserver side programming更新于 2025/5/30 17:22:17

要在 C# 中设置常量,请使用 const 关键字。初始化常量后,更改它将导致错误。

让我们声明并初始化一个常量字符串 −

const string one= "Amit";

现在您无法修改字符串 one,因为它已设置为常量。

让我们看一个例子,其中我们有三个常量字符串。声明 − 后我们无法修改它。

示例

using System;

class Demo {
   const string one= "Amit";

   static void Main() {
      // 显示第一个常量字符串
      Console.WriteLine(one);

      const string two = "Tom";
      const string three = "Steve";

      // 编译时错误
      // one = "David";

      Console.WriteLine(two);
      Console.WriteLine(three);
   }
}

输出

Amit
Tom
Steve

如上所示,如果我尝试修改常量字符串一的值,则会显示错误 −

// compile-time error
// one = "David";

相关文章