跳转到内容

C Sharp 常量

来自代码酷


简介[编辑 | 编辑源代码]

在C#编程中,常量(Constant)是一种在程序运行期间其值不可改变的标识符。常量通过`const`关键字声明,必须在声明时初始化,且只能使用编译时可确定的值(如字面量、其他常量或数学表达式)。常量提供以下核心优势:

  • 类型安全:编译器会检查常量值的合法性
  • 性能优化:编译时直接替换为实际值,无需运行时计算
  • 代码可读性:通过命名表达固定值的含义

声明语法[编辑 | 编辑源代码]

C#常量的基本声明格式如下:

const 数据类型 常量名 = ;

基础示例[编辑 | 编辑源代码]

const double PI = 3.14159;
const int MaxUsers = 100;
const string Greeting = "Hello, World!";

常量类型[编辑 | 编辑源代码]

C#支持以下类型的常量:

常量类型表
数据类型 示例 说明 数值类型 const int Count = 5; 包括整数和浮点数 布尔类型 const bool IsEnabled = true; 仅能是true/false 字符串类型 const string Path = "C:\\Temp"; 必须使用双引号 枚举类型 const DayOfWeek FirstDay = DayOfWeek.Monday; 必须是枚举成员 null引用 const object NullObj = null; 仅适用于引用类型

编译时常量 vs 运行时常量[编辑 | 编辑源代码]

C#中存在两种"常量"概念:

flowchart LR A[常量类型] --> B[编译时常量 const] A --> C[运行时常量 readonly]

const与readonly对比
特性 const readonly 初始化时机 声明时 声明时或构造函数中 内存分配 编译时替换 运行时分配 适用类型 基本类型/string 任意类型 性能 更优 稍低 灵活性

readonly示例[编辑 | 编辑源代码]

public class Config {
    public readonly string LogPath;
    
    public Config() {
        LogPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    }
}

数学常量应用[编辑 | 编辑源代码]

科学计算中常使用数学常量,例如计算圆面积:

const double PI = 3.141592653589793;
double radius = 5;
double area = PI * Math.Pow(radius, 2);
Console.WriteLine($"半径为{radius}的圆面积: {area:F2}");

输出:

半径为5的圆面积: 78.54

实际应用案例[编辑 | 编辑源代码]

场景1:游戏开发[编辑 | 编辑源代码]

在游戏配置中使用常量定义基础参数:

public class GameSettings {
    public const int MaxEnemies = 50;
    public const float Gravity = 9.8f;
    public const string SaveFile = "game.sav";
    
    public static void ShowSettings() {
        Console.WriteLine($"最大敌人数: {MaxEnemies}");
        Console.WriteLine($"重力系数: {Gravity}");
    }
}

场景2:Web应用[编辑 | 编辑源代码]

定义HTTP状态码常量:

public class HttpCodes {
    public const int OK = 200;
    public const int NotFound = 404;
    public const int ServerError = 500;
    
    public static string GetMessage(int code) {
        return code switch {
            OK => "请求成功",
            NotFound => "资源未找到",
            ServerError => "服务器错误",
            _ => "未知状态"
        };
    }
}

高级主题[编辑 | 编辑源代码]

常量表达式[编辑 | 编辑源代码]

C#允许使用包含运算符的常量表达式:

const int SecondsPerMinute = 60;
const int SecondsPerHour = SecondsPerMinute * 60;
const double Radians = 180 / Math.PI;  // 需要using System

条件编译常量[编辑 | 编辑源代码]

配合预处理指令使用:

#define DEBUG
const int MaxItems = 100;

#if DEBUG
    const string Mode = "调试模式";
#else
    const string Mode = "发布模式";
#endif

最佳实践[编辑 | 编辑源代码]

  • 使用全大写命名风格(如MAX_VALUE
  • 将相关常量组织在静态类中
  • 避免过度使用常量导致代码僵化
  • 对于可能变化的值,考虑使用readonly或配置文件

限制与注意事项[编辑 | 编辑源代码]

1. 不能使用static修饰(常量隐式静态) 2. 不能用于数组或自定义类实例(除null外) 3. 引用类型常量只能是stringnull 4. 循环引用会导致编译错误:

const int A = B + 1;  // 错误
const int B = A + 1;

总结[编辑 | 编辑源代码]

C#常量是类型安全、不可变的编译时常量,通过const关键字声明。它们:

  • 提高代码可读性和可维护性
  • 在编译时被替换为实际值
  • 适用于不会改变的基础值
  • readonly形成互补关系

掌握常量的正确使用方式,可以使您的C#代码更加健壮和高效。