如何在 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