在 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