个性化阅读
专注于IT技术分析

C#中的readonly和const关键字之间的区别

点击下载

在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 = "srcmini" ;
  
     //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: srcmini

在C#中, 你可以使用只读关键字来声明一个只读变量。此只读关键字表明, 只有在声明变量或在声明该变量的相同类的构造函数中才可以分配该变量。

例子:

//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与const关键字

readonly关键字 const关键字
在C#中, 可以使用readonly关键字创建readonly字段 在C#中, 使用const关键字创建常量字段。
ReadOnly是运行时常量。 const是一个编译时间常数。
只读字段的值可以更改。 const字段的值不能更改。
不能在方法内部声明。 可以在方法内部声明。
在只读字段中, 我们可以在声明和构造器部分中分配值。 在const字段中, 我们只能在声明部分中分配值。
它可以与静态修饰符一起使用。 不能与静态修饰符一起使用。

赞(0)
未经允许不得转载:srcmini » C#中的readonly和const关键字之间的区别

评论 抢沙发

评论前必须登录!