如何在 C# 中声明和初始化常量字符串?
若要在 C# 中设置常量,请使用 const 关键字。在初始化常量后,如果对它进行更改,将导致错误。
我们来声明和初始化一个常量字符串 −
const string one= "Amit";
现在你无法修改字符串 one,因为它已设为常量。
我们看一个示例,其中我们有三个常量字符串。在声明后我们无法修改它们 −
示例
using System;
class Demo {
const string one= "Amit";
static void Main() {
// displaying first constant string
Console.WriteLine(one);
const string two = "Tom";
const string three = "Steve";
// compile-time error
// one = "David";
Console.WriteLine(two);
Console.WriteLine(three);
}
}输出
Amit Tom Steve
如上所示,如果我尝试修改常量字符串 one 的值,那么它将显示一个错误 −
// compile-time error // one = "David";
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP