在 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";
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP