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

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

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

const string one= "Amit";

现在您不能修改字符串一,因为它被设置为常量。

让我们看一个例子,其中我们有三个常量字符串。我们不能在声明后修改它 -

示例

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

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

// 编译时错误

// one = "David";

以上是 如何在 C# 中声明和初始化常量字符串? 的全部内容, 来源链接: utcz.com/z/362214.html

回到顶部