C#?常量(Constant)的使用小結(jié)
常量(Constant)是指在程序運(yùn)行過程中值永遠(yuǎn)不會(huì)改變的數(shù)據(jù)。在 C# 中,合理使用常量可以提高代碼的可讀性、可維護(hù)性和執(zhí)行效率。
一、為什么要使用常量
假設(shè)代碼中存在大量魔法數(shù)字(Magic Number):
double area = 3.1415926 * r * r;
if (status == 1)
{
Console.WriteLine("運(yùn)行中");
}閱讀代碼時(shí):
3.1415926表示什么?1表示什么狀態(tài)?
改成常量:
const double PI = 3.1415926;
const int STATUS_RUNNING = 1;
double area = PI * r * r;
if (status == STATUS_RUNNING)
{
Console.WriteLine("運(yùn)行中");
}優(yōu)點(diǎn):
- 代碼語義清晰
- 修改方便
- 減少出錯(cuò)概率
二、const關(guān)鍵字
基本語法
const 數(shù)據(jù)類型 常量名 = 值;
例如:
const int MaxUserCount = 100; const string CompanyName = "OpenAI"; const double PI = 3.1415926;
完整示例
using System;
class Program
{
const string SYSTEM_NAME = "倉(cāng)儲(chǔ)管理系統(tǒng)";
const int MAX_RETRY = 3;
static void Main()
{
Console.WriteLine(SYSTEM_NAME);
Console.WriteLine(MAX_RETRY);
}
}輸出:
倉(cāng)儲(chǔ)管理系統(tǒng) 3
三、const的特點(diǎn)
1. 必須初始化
錯(cuò)誤寫法:
const int Age;
編譯錯(cuò)誤:
The const field requires a value
正確寫法:
const int Age = 18;
2. 不能修改
const int Age = 18; Age = 20;
編譯錯(cuò)誤:Cannot assign to 'Age' because it is read-only
3. 編譯時(shí)確定值
const int A = 10; const int B = A + 20;
編譯器直接計(jì)算:
const int B = 30;
4. 隱式靜態(tài)
雖然沒有寫 static:
public class Config
{
public const string Version = "1.0";
}訪問:
Console.WriteLine(Config.Version);
實(shí)際上:
public static const string Version = "1.0";
(編譯器內(nèi)部處理)
四、const支持的數(shù)據(jù)類型
1.支持
1.整數(shù)
const int Age = 18; const long Count = 1000000;
2.浮點(diǎn)數(shù)
const double PI = 3.14; const float Rate = 0.8f;
布爾值
const bool IsEnabled = true;
字符
const char Grade = 'A';
字符串
const string Name = "OpenAI";
枚舉
enum Status
{
Running,
Stop
}
const Status Current = Status.Running;2.不支持
DateTime
const DateTime Now = DateTime.Now;
錯(cuò)誤:The type DateTime is not valid for a const field
Guid
const Guid Id = Guid.NewGuid();
錯(cuò)誤
List
const List<int> list = new List<int>();
錯(cuò)誤
五、常量命名規(guī)范
微軟推薦(Pascal命名)
public const int MaxRetryCount = 3; public const string CompanyName = "OpenAI";
全大寫(傳統(tǒng)風(fēng)格)
public const int MAX_RETRY_COUNT = 3; public const string COMPANY_NAME = "OpenAI";
現(xiàn)代 C# 項(xiàng)目更推薦:
MaxRetryCount
六、const與readonly區(qū)別
這是面試高頻題。
const
public const int Age = 18;
特點(diǎn):
- 編譯時(shí)確定
- 必須賦值
- 永遠(yuǎn)不能修改
readonly
public readonly int Age;
public Person()
{
Age = 18;
}特點(diǎn):
- 運(yùn)行時(shí)確定
- 構(gòu)造函數(shù)可賦值
- 之后不可修改
對(duì)比表
| 項(xiàng)目 | const | readonly |
|---|---|---|
| 賦值時(shí)間 | 編譯時(shí) | 運(yùn)行時(shí) |
| 修改 | 不允許 | 構(gòu)造完成后不允許 |
| 是否靜態(tài) | 是 | 否 |
| 支持對(duì)象 | 否 | 是 |
| 支持DateTime | 否 | 是 |
七、static readonly
企業(yè)開發(fā)最常用。
示例
public static readonly DateTime StartTime =
DateTime.Now;Guid
public static readonly Guid EmptyGuid =
Guid.Empty;集合
public static readonly List<string> Roles =
new List<string>
{
"Admin",
"User"
};八、const的底層原理
定義:
public const int MaxCount = 100;
使用:
Console.WriteLine(MaxCount);
編譯后:
Console.WriteLine(100);
編譯器直接替換。
這叫:
編譯時(shí)常量替換(Compile-time Constant Substitution)
九、跨程序集使用const的坑
項(xiàng)目A:
public const int Version = 1;
項(xiàng)目B引用A:
Console.WriteLine(Config.Version);
編譯后:
Console.WriteLine(1);
后來A修改:
public const int Version = 2;
如果只重新發(fā)布A:B仍然輸出1
因?yàn)锽已經(jīng)把值寫死了。
解決方案
使用:
public static readonly int Version = 2;
運(yùn)行時(shí)讀取:
Console.WriteLine(Config.Version);
無需重新編譯引用項(xiàng)目。
十、常量類設(shè)計(jì)模式
很多企業(yè)項(xiàng)目這樣寫:
public static class SystemConstants
{
public const string Admin = "Admin";
public const string User = "User";
public const int MaxRetry = 3;
public const string DefaultPassword = "123456";
}調(diào)用:
if(role == SystemConstants.Admin)
{
Console.WriteLine("管理員");
}十一、實(shí)際項(xiàng)目案例
狀態(tài)碼
public static class OrderStatus
{
public const int Created = 0;
public const int Paying = 1;
public const int Success = 2;
public const int Cancel = 3;
}API地址
推薦:
public static readonly string ApiUrl =
"https://api.xxx.com";不推薦:
public const string ApiUrl =
"https://api.xxx.com";因?yàn)榭赡茏兏?/p>
十二、面試常見問題
1. const和readonly有什么區(qū)別?
- const:編譯時(shí)常量
- readonly:運(yùn)行時(shí)只讀
2. 為什么DateTime不能定義為const?
因?yàn)椋?/p>
DateTime.Now
3. 企業(yè)開發(fā)更推薦const還是readonly?
一般規(guī)則:
固定數(shù)學(xué)值、狀態(tài)碼 → const 配置項(xiàng)、對(duì)象實(shí)例 → static readonly
最佳實(shí)踐總結(jié)
// 1. 數(shù)學(xué)常量
public const double PI = 3.1415926;
// 2. 狀態(tài)碼
public const int Success = 200;
// 3. 配置值
public static readonly string ApiUrl =
"https://api.example.com";
// 4. 對(duì)象
public static readonly Guid EmptyGuid =
Guid.Empty;
// 5. 枚舉優(yōu)先于狀態(tài)常量
public enum OrderStatus
{
Created,
Paying,
Success,
Cancel
}在實(shí)際企業(yè)級(jí) C# 開發(fā)(ASP.NET Core、WPF、WinForms、MES、WMS、ERP、數(shù)字孿生系統(tǒng))中,通常遵循:
優(yōu)先使用 enum 表示狀態(tài),使用 const 表示真正永不變化的值,使用 static readonly 表示運(yùn)行時(shí)確定但只讀的數(shù)據(jù)。
到此這篇關(guān)于C# 常量(Constant)詳解的文章就介紹到這了,更多相關(guān)C# 常量?jī)?nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)Word與TXT文本格式互轉(zhuǎn)的操作代碼
在現(xiàn)代辦公自動(dòng)化和數(shù)據(jù)處理流程中,經(jīng)常需要在不同的文檔格式之間進(jìn)行轉(zhuǎn)換,將Word文檔(.doc, .docx)轉(zhuǎn)換為純文本(.txt)可以方便地提取文字內(nèi)容用于數(shù)據(jù)分析、內(nèi)容索引或簡(jiǎn)化分享,本文將分享如何使用Spire.Doc for .NET實(shí)現(xiàn)TXT文本文件與Word文檔之間的雙向轉(zhuǎn)換2025-09-09
C#實(shí)現(xiàn)動(dòng)態(tài)數(shù)字時(shí)鐘和日歷
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)動(dòng)態(tài)數(shù)字時(shí)鐘和日歷的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06
C#實(shí)現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法,可實(shí)現(xiàn)系統(tǒng)服務(wù)的啟動(dòng)和停止功能,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
C#調(diào)用dos窗口獲取相關(guān)信息的方法
這篇文章主要介紹了C#調(diào)用dos窗口獲取相關(guān)信息的方法,涉及C#調(diào)用dos窗口及進(jìn)程操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08
C# IP地址與整數(shù)之間轉(zhuǎn)換的具體方法
這篇文章介紹了C# IP地址與整數(shù)之間轉(zhuǎn)換的具體方法,有需要的朋友可以參考一下2013-10-10
C#動(dòng)態(tài)獲取系統(tǒng)當(dāng)前日期與時(shí)間的方法詳解
在C#編程中,動(dòng)態(tài)獲取系統(tǒng)當(dāng)前的日期和時(shí)間是一項(xiàng)基礎(chǔ)而關(guān)鍵的操作,文詳細(xì)介紹了?DateTime.Now?、?DateTime.Today?和?DateTime.UtcNow?等常用屬性,并結(jié)合示例代碼演示了如何獲取和格式化當(dāng)前時(shí)間,希望對(duì)大家有所幫助2025-11-11

