当前位置:网站首页>C - readonly and const keywords

C - readonly and const keywords

2022-07-25 23:48:00 wumingxiaoyao

introduction

Constants are often used in program design ,C# In language readonly, const Define constants , How to accurately define constants , What's the difference between them ?

Static and dynamic constants

Before understanding these two keywords , Let's first look at static constants and dynamic constants .

  • static const :
    The value is determined at compile time , Must be initialized at declaration time and cannot be changed later .
  • Dynamic constants :
    Determine the value at run time , Can only be initialized in a declaration or constructor .

const

Use const Keyword to declare a constant field or constant local variable , It's a static constant . Constant fields and constant local variables Cannot contain variables and cannot be modified . Constants can be numbers 、 Boolean value 、 String or null quote . Don't create constants to represent information that you need to change at any time .

const matters needing attention

  1. const and static Can't be used together , Because constant fields are implicitly static ,const After compiling static Static field .
     Insert picture description here

  2. Out-of-service new Keyword initializes a static constant , Even for a value type
     Insert picture description here

  3. const Constants cannot be variables
     Insert picture description here

const Constant access

Class directly accesses const Constant .

namespace ConsoleApp1
{
    
    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;
        }
    }
    public class TestConst
    {
    
        public static void Main(string[] args)
        {
    
            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 */

readonly

readonly Fields can only be assigned values during declaration or in the constructor of the same class . You can assign and reassign read-only fields multiple times in field declarations and constructors , Is a dynamic constant .

static readonly Static read-only fields , Read only fields are not implicitly static , So expose it at the class level , You must explicitly use static keyword .

After the constructor exits , Can't assign readonly Field . This rule has different meanings for value type and reference type :

  • Because the value type directly contains data , Therefore, it belongs to readonly Fields of value type are immutable .
  • Because reference types contain references to their data , Therefore, it belongs to readonly Fields of reference type must always reference the same object . The object is mutable . readonly Modifiers prevent fields from being replaced with other instances of the reference type . however , Modifiers do not prevent modifying the instance data of a field through a read-only field .
     Insert picture description here

readonly Constant access

namespace ConsoleApp1
{
    
    class SamplePoint
    {
    
        public int x;
        // Initialize a readonly field
        public readonly int y = 25;
        public readonly int z;
        public static readonly string LAGUAGE = "C#";

        public SamplePoint()
        {
    
            // Initialize a readonly instance field
            z = 24;
        }

        public SamplePoint(int p1, int p2, int p3)
        {
    
            x = p1;
            y = p2;
            z = p3;
        }
    }
    public class TestConst
    {
    
        public static void Main(string[] args)
        {
    
            Console.WriteLine($"SamplePoint.LAGUAGE = {
      SamplePoint.LAGUAGE}");
            SamplePoint p1 = new SamplePoint(11, 21, 32);   // OK
            Console.WriteLine($"p1: x={
      p1.x}, y={
      p1.y}, z={
      p1.z}");
            SamplePoint p2 = new SamplePoint();
            p2.x = 55;   // OK
            //p2.y = 66;// Error
            Console.WriteLine($"p2: x={
      p2.x}, y={
      p2.y}, z={
      p2.z}");
        }
    }
}
/* output SamplePoint.LAGUAGE = C# p1: x=11, y=21, z=32 p2: x=55, y=25, z=24 */

const and readonly difference

  1. Conceptual differences
    readonly Indicates read-only , Dynamic constants , Run time determination value ,const Represents a static constant , The value is determined at compile time .
    such as : The date of birth of a person can be defined as const Constant , Once declared, the value will not change , And people's age age It can be defined as readonly, You can calculate the age according to the date of birth in the constructor .
  2. The scope of decoration is different
    readonly It can only be modified field, Can't be decorated local variable,const Modifiable field and local variable.
     Insert picture description here
  3. Type difference
    const It can only be modified primitive type( Numbers 、 Boolean value , character ) And very special reference types string and null(string It's an immutable string , Each modification , Are equivalent to re creating a ), Why not decorate other reference types , Because other reference types cannot know their exact values at compile time . Out-of-service new Keyword initializes a static constant .
    readonly Can be any data type , It can be used new Keyword initializes a dynamic constant .
  4. const The default variable is static Class variables , Cannot add static modification ,readonly Default is not , It needs to be specially added static To become a class variable .
  5. assignment
    const Can only be assigned when declaring , Cannot assign values externally ,readonly You can assign values externally , But it can only be assigned by constructor .
  6. efficiency
    const Modifier constants focus on efficiency ;readonly Modifier constants focus on flexibility .
    const Decorated constants have no memory consumption ;readonly Because you need to save constants , So there is memory consumption .
原网站

版权声明
本文为[wumingxiaoyao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/206/202207252340197350.html