在C#中,使用const关键字来声明常量字段和常量局部变量。在整个程序中,常量字段的值是相同的,换句话说,一旦分配了常量字段,该字段的值就不会更改。在C#中,常量字段和局部变量不是变量,常量是数字,字符串,空引用,布尔值。
例子:
// C# program to illustrate the
// use of const keyword
using System;
class GFG {
// Constant fields
public const int myvar = 10;
public const string str = "GeeksforGeeks";
// Main method
static public void Main()
{
// Display the value of Constant fields
Console.WriteLine("The value of myvar: {0}", myvar);
Console.WriteLine("The value of str: {0}", str);
}
}
输出:
The value of myvar: 10
The value of str: GeeksforGeeks
在C#中,可以使用readonly关键字声明一个readonly变量。此只读关键字表明,只有在声明变量或在声明该变量的相同类的构造函数中才可以分配该变量。
例子:
// C# program to illustrate the use
// of the readonly keyword
using System;
class GFG {
// readonly variables
public readonly int myvar1;
public readonly int myvar2;
// Values of the readonly
// variables are assigned
// Using constructor
public GFG(int b, int c)
{
myvar1 = b;
myvar2 = c;
Console.WriteLine("Display value of myvar1 {0}, "+
"and myvar2 {1}", myvar1, myvar2);
}
// Main method
static public void Main()
{
GFG obj1 = new GFG(100, 200);
}
}
输出:
Display value of myvar1 100, and myvar2 200
只读与常量关键字
ReadOnly Keyword | Const Keyword |
---|---|
In C#, readonly fields can be created using readonly keyword | In C#, constant fields are created using const keyword. |
ReadOnly is a runtime constant. | Const is a compile time constant. |
The value of readonly field can be changed. | The value of the const field can not be changed. |
It cannot be declared inside the method. | It can be declared inside the method. |
In readonly fields, we can assign values in declaration and in the contructor part. | In const fields, we can only assign values in declaration part. |
It can be used with static modifiers. | It cannot be used with static modifiers. |