修饰符:const
const 关键字用于修改字段或局部变量的声明。它指定字段或局部变量的值是常数,不能被修改。例如:
const int x = 0; public const double gravitationalConstant = 6.673e-11; private const string productName = "Visual C#"; |
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!
备注
常数声明的类型指定声明引入的成员类型。常数表达式必须产生具有目标类型或者可隐式转换为目标类型的类型的值。
常数表达式是在编译时可被完全计算的表达式。因此,对于引用类型的常数,可能的值只能是 string 和 null。
常数声明可以声明多个常数,例如:
public const double x = 1.0, y = 2.0, z = 3.0; |
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!
不允许在常数声明中使用 static 修饰符。
常数可以参与常数表达式,如下所示:
public const int c1 = 5; public const int c2 = c1 + 100; |
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!
![]() |
---|
|
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!
示例
C# | |
---|---|
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() { SampleClass mC = new SampleClass(11, 22); Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); Console.WriteLine("c1 = {0}, c2 = {1}", SampleClass.c1, SampleClass.c2 ); } } /* Output x = 11, y = 22 c1 = 5, c2 = 10 */ |
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!
此示例说明如何将常数用作局部变量。
C# | |
---|---|
public class SealedTest { static void Main() { const int c = 707; Console.WriteLine("My local constant = {0}", c); } } // Output: My local constant = 707 |
本在线速查手册由www.w♡3♡x♡u♡e.com提供,请勿盗用!