const 关键字

您所在的位置:网站首页 const可以修改对象吗 const 关键字

const 关键字

2024-07-10 11:13| 来源: 网络整理| 查看: 265

const(C# 参考) 项目06/05/2023

使用 const 关键字来声明某个常量字段或局部变量。 常量字段和常量局部变量不是变量并且不能修改。 常量可以为数字、布尔值、字符串或 null 引用。 不要创建常量来表示你需要随时更改的信息。 例如,不要使用常量字段来存储服务的价格、产品版本号或公司的品牌名称。 这些值会随着时间发生变化;因为编译器会传播常量,所以必须重新编译通过库编译的其他代码以查看更改。 另请参阅 readonly 关键字。 例如:

const int X = 0; public const double GravitationalConstant = 6.673e-11; private const string ProductName = "Visual C#";

从 C# 10 开始,如果所使用的所有表达式也是常量字符串,则内插字符串可以是常量。 此功能可以改进生成常量字符串的代码:

const string Language = "C#"; const string Platform = ".NET"; const string FullProductName = $"{Platform} - Language: {Language}"; 备注

常数声明的类型指定声明引入的成员类型。 某个局部变量或常量字段的初始值设定项必须是一个可以隐式转换为目标类型的常量表达式。

常数表达式是在编译时可被完全计算的表达式。 因此,对于引用类型的常数,可能的值只能是字符串和空引用。

常数声明可以声明多个常数,例如:

public const double X = 1.0, Y = 2.0, Z = 3.0;

不允许在常数声明中使用 修饰符。

常数可以参与常数表达式,如下所示:

public const int C1 = 5; public const int C2 = C1 + 100;

注意

readonly 关键字与 const 关键字不同。 const 字段只能在该字段的声明中初始化。 字段可以在声明或构造函数中初始化。 因此,根据所使用的构造函数,readonly 字段可能具有不同的值。 另外,虽然 const 字段是编译时常量,但 readonly 字段可用于运行时常量,如此行所示:public static readonly uint l1 = (uint)DateTime.Now.Ticks;

示例 public class ConstTest { class SampleClass { public int x; public int y; public const int C1 = 5; public const int C2 = C1 + 5; public SampleClass(int p1, int p2) { x = p1; y = p2; } } static void Main() { var mC = new SampleClass(11, 22); Console.WriteLine($"x = {mC.x}, y = {mC.y}"); Console.WriteLine($"C1 = {SampleClass.C1}, C2 = {SampleClass.C2}"); } } /* Output x = 11, y = 22 C1 = 5, C2 = 10 */

以下示例演示如何声明某个本地常量:

public class SealedTest { static void Main() { const int C = 707; Console.WriteLine($"My local constant = {C}"); } } // Output: My local constant = 707 C# 语言规范

有关更多信息,请参阅 C# 语言规范的以下部分:

常量 常量表达式 另请参阅 C# 关键字 readonly


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3