C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# 常量

C# 常量(Constant)的使用小结

作者:逝水无殇

本文系统介绍了C#中常量的使用与实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

常量(Constant)是指在程序运行过程中值永远不会改变的数据。在 C# 中,合理使用常量可以提高代码的可读性、可维护性和执行效率。

一、为什么要使用常量

假设代码中存在大量魔法数字(Magic Number):

double area = 3.1415926 * r * r;

if (status == 1)
{
    Console.WriteLine("运行中");
}

阅读代码时:

改成常量:

const double PI = 3.1415926;
const int STATUS_RUNNING = 1;

double area = PI * r * r;

if (status == STATUS_RUNNING)
{
    Console.WriteLine("运行中");
}

优点:

二、const关键字

基本语法

const 数据类型 常量名 = 值;

例如:

const int MaxUserCount = 100;
const string CompanyName = "OpenAI";
const double PI = 3.1415926;

完整示例

using System;

class Program
{
    const string SYSTEM_NAME = "仓储管理系统";
    const int MAX_RETRY = 3;

    static void Main()
    {
        Console.WriteLine(SYSTEM_NAME);
        Console.WriteLine(MAX_RETRY);
    }
}

输出:

仓储管理系统
3

三、const的特点

1. 必须初始化

错误写法:

const int Age;

编译错误:

The const field requires a value

正确写法:

const int Age = 18;

2. 不能修改

const int Age = 18;
Age = 20;

编译错误:Cannot assign to 'Age' because it is read-only

3. 编译时确定值

const int A = 10;
const int B = A + 20;

编译器直接计算:

const int B = 30;

4. 隐式静态

虽然没有写 static:

public class Config
{
    public const string Version = "1.0";
}

访问:

Console.WriteLine(Config.Version);

实际上:

public static const string Version = "1.0";

(编译器内部处理)

四、const支持的数据类型

1.支持

1.整数

const int Age = 18; 
const long Count = 1000000;

2.浮点数

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;

错误:The type DateTime is not valid for a const field

Guid

const Guid Id = Guid.NewGuid();

错误

List

const List<int> list = new List<int>();

错误

五、常量命名规范

微软推荐(Pascal命名)

public const int MaxRetryCount = 3;
public const string CompanyName = "OpenAI";

全大写(传统风格)

public const int MAX_RETRY_COUNT = 3;
public const string COMPANY_NAME = "OpenAI";

现代 C# 项目更推荐:

MaxRetryCount

六、const与readonly区别

这是面试高频题。

const

public const int Age = 18;

特点:

readonly

public readonly int Age;

public Person()
{
    Age = 18;
}

特点:

对比表

项目constreadonly
赋值时间编译时运行时
修改不允许构造完成后不允许
是否静态
支持对象
支持DateTime

七、static readonly

企业开发最常用。

示例

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);

编译器直接替换。

这叫:

编译时常量替换(Compile-time Constant Substitution)

九、跨程序集使用const的坑

项目A:

public const int Version = 1;

项目B引用A:

Console.WriteLine(Config.Version);

编译后:

Console.WriteLine(1);

后来A修改:

public const int Version = 2;

如果只重新发布A:B仍然输出1

因为B已经把值写死了。

解决方案

使用:

public static readonly int Version = 2;

运行时读取:

Console.WriteLine(Config.Version);

无需重新编译引用项目。

十、常量类设计模式

很多企业项目这样写:

public static class SystemConstants
{
    public const string Admin = "Admin";

    public const string User = "User";

    public const int MaxRetry = 3;

    public const string DefaultPassword = "123456";
}

调用:

if(role == SystemConstants.Admin)
{
    Console.WriteLine("管理员");
}

十一、实际项目案例

状态码

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";

因为可能变更。

十二、面试常见问题

1. const和readonly有什么区别?

2. 为什么DateTime不能定义为const?

因为:

DateTime.Now

3. 企业开发更推荐const还是readonly?

一般规则:

固定数学值、状态码 → const
配置项、对象实例 → static readonly

最佳实践总结

// 1. 数学常量
public const double PI = 3.1415926;

// 2. 状态码
public const int Success = 200;

// 3. 配置值
public static readonly string ApiUrl =
    "https://api.example.com";

// 4. 对象
public static readonly Guid EmptyGuid =
    Guid.Empty;

// 5. 枚举优先于状态常量
public enum OrderStatus
{
    Created,
    Paying,
    Success,
    Cancel
}

在实际企业级 C# 开发(ASP.NET Core、WPF、WinForms、MES、WMS、ERP、数字孪生系统)中,通常遵循:

优先使用 enum 表示状态,使用 const 表示真正永不变化的值,使用 static readonly 表示运行时确定但只读的数据。

到此这篇关于C# 常量(Constant)详解的文章就介绍到这了,更多相关C# 常量内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文