1. Only C # built-in types (Int,double,long, etc.) can be declared as const, and results, classes, and arrays cannot be declared as Const.
2. ReadOnly is a modifier used on a field that is accessed directly by the class name. field.
3. The const must be initialized in the declaration. Can not be modified after that.
4. ReadOnly can be initialized in a declaration or initialized in a constructor, and other circumstances cannot be modified.
namespace Const_and_readonly {class Program {static void Main (string[] args) {Conso Le. WriteLine ("Half a year have {0} moths", CALENDAR.MOTHS/2);
Direct class name. field Access Const field Calendar test1 = new Calendar (); Console.WriteLine ("Every year has {0} weeks and {1} days", Test1._weeks, test1._days);//readonly field accesses the Calendar by instance test2 =
New Calendar (31, 4);
Console.WriteLine ("January has {0} weeks and {1} days", Test2._weeks, Test2. _days);
Console.readkey (); Class Calendar {public const int moths =//const must initialize the public readonly int _days=365 in the Declaration;//readonly initialize public in the Declaration
readonly int _weeks; Public calendar ()//readonly initializes {_weeks = ' public calendar ' (int days,int weeks) within the constructor//readonly Initialize {_days = d in the constructor
Ays
_weeks = weeks; public void SetValue (int days,int weeks) {//_days = days; Cannot assign value to read-only field//_weeks = weeks; Cannot assign values to read-only fields}}
The above is a small set to introduce the C # in the const and readonly modifier usage detailed, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!