c difference between read only fields and constants and use instances of static constructors

  • 2020-05-27 07:02:54
  • OfStack


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    /// <summary>
    ///  The author :it jin 
    ///  Function: c# The difference between read-only fields and constants, and the use of static constructors 
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(test.a);
            Console.WriteLine(test.b);
            Console.Read();

        }
    
    }
    public class test
    {
        public static readonly int b;// Read-only fields are available static The keyword , Read-only fields can be assigned without initialization, and read-only fields can only be assigned when constructors or variables are initialized 
        public const int a=1;// Constants cannot be used static The keyword , Constants must be initialized and assigned at the time of definition 

       static test()// Static constructor, called before class instantiation , And only perform 1 time 
        {

            b = 2;// Because it is a read-only field, it can only be initialized in the constructor and changed to a read-only field static Type, so you need to assign it in the static constructor 
        }
        void aa()
        {
            //a = 1; error 
            //b=1; error 
        }
        
    }
}


Related articles: