1.使用const關(guān)鍵字聲明常量字段和常量局部變量時(shí),常量字段和常量局部變量不是變量且不能改變。==>常量在程序中是不能改變的,而變量是可以改變的。常量可以為數(shù)字、布爾值、字符串或 null 引用。 不要?jiǎng)?chuàng)建常量來表示你需要隨時(shí)更改的信息。 不允許在常數(shù)聲明中使用 static 修飾符。
2.readonly 關(guān)鍵字是可以在字段上使用的修飾符。 當(dāng)字段聲明包括 readonly 修飾符時(shí),該聲明引入的字段賦值只能作為聲明的一部分出現(xiàn),或者出現(xiàn)在同一類的構(gòu)造函數(shù)中。
3.const為編譯時(shí)常量,不能構(gòu)建復(fù)雜的數(shù)據(jù)類型。readonly為運(yùn)行時(shí)常量,可以構(gòu)建復(fù)雜的數(shù)據(jù)類型。
readonly 關(guān)鍵字與 const 關(guān)鍵字不同。 const 字段只能在該字段的聲明中初始化。 readonly 字段可以在聲明或構(gòu)造函數(shù)中初始化。 因此,根據(jù)所使用的構(gòu)造函數(shù),readonly 字段可能具有不同的值。 另外,const 字段為編譯時(shí)常數(shù)而 readonly 字段可用于運(yùn)行時(shí)常量。
public static readonly uint timeStamp = (uint)DateTime.Now.Tick;
調(diào)用時(shí)也不同
class PRogram { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; //直接使用const值 Console.WriteLine(sample.constValue); //實(shí)例化對(duì)象后使用 sample2 s2 = new sample2(); Console.WriteLine(s2.readonlyValue); Console.Read(); } class sample { public const int constValue = 10; } class sample2 { public readonly int readonlyValue = 20; } }
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注