日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C#const常量詳細介紹

C#語言有很多值得學(xué)習(xí)的地方,這里我們主要介紹C# const常量,包括介紹readonly和const所修飾的變量等方面。

我們提供的服務(wù)有:做網(wǎng)站、成都網(wǎng)站設(shè)計、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、撫州ssl等。為近1000家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的撫州網(wǎng)站制作公司

一般情況下,如果你需要聲明的常量是普遍公認的并作為單個使用,例如圓周率,黃金分割比例等。你可以考慮使用C# const常量,如:public const double PI = 3.1415926;。如果你需要聲明常量,不過這個常量會隨著實際的運行情況而決定,那么,readonly常量將會是一個不錯的選擇,例如上面***個例子的訂單號Order.ID。

另外,如果要表示對象內(nèi)部的默認值的話,而這類值通常是常量性質(zhì)的,那么也可以考慮const。更多時候我們對源代碼進行重構(gòu)時(使用Replace Magic Number with Symbolic Constant),要去除魔數(shù)(Magic Number)的影響都會借助于const的這種特性。

對于readonly和const所修飾的變量究竟是屬于類級別的還是實例對象級別的問題,我們先看看如下代碼:

 
 
 
  1. using System;
  2. namespace ConstantLab
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Constant c = new Constant(3);
  9. Console.WriteLine("ConstInt = " + Constant.ConstInt.ToString());
  10. Console.WriteLine("ReadonlyInt = " + c.ReadonlyInt.ToString());
  11. Console.WriteLine("InstantReadonlyInt = " + c.InstantReadonlyInt.ToString());
  12. Console.WriteLine("StaticReadonlyInt = " + Constant.StaticReadonlyInt.ToString());
  13. Console.WriteLine("Press any key to continue");
  14. Console.ReadLine();
  15. }
  16. }
  17. class Constant
  18. {
  19. public Constant(int instantReadonlyInt)
  20. {
  21. InstantReadonlyInt = instantReadonlyInt;
  22. }
  23. public const int ConstInt = 0;
  24. public readonly int ReadonlyInt = 1;
  25. public readonly int InstantReadonlyInt;
  26. public static readonly int StaticReadonlyInt = 4;
  27. }
  28. }

使用Visual C#在 Main()里面使用IntelliSence插入Constant的相關(guān)field的時候,發(fā)現(xiàn)ReadonlyInt和 InstantReadonlyInt需要指定Constant的實例對象;而ConstInt和StaticReadonlyInt卻要指定 Constant class(參見上面代碼)??梢?,用const或者static readonly修飾的常量是屬于類級別的;而readonly修飾的,無論是直接通過賦值來初始化或者在實例構(gòu)造函數(shù)里初始化,都屬于實例對象級別。

一般情況下,如果你需要表達一組相關(guān)的編譯時確定常量,你可以考慮使用枚舉類型(enum),而不是把多個C# const常量直接嵌入到class中作為field,不過這兩種方式?jīng)]有絕對的孰優(yōu)孰劣之分。

 
 
 
  1. using System;
  2. enum CustomerKind
  3. {
  4. SuperVip,
  5. Vip,
  6. Normal
  7. }
  8. class Customer
  9. {
  10. public Customer(string name, CustomerKind kind)
  11. {
  12. m_Name = name;
  13. m_Kind = kind;
  14. }
  15. private string m_Name;
  16. public string Name
  17. {
  18. get { return m_Name; }
  19. }
  20. private CustomerKind m_Kind;
  21. public CustomerKind Kind
  22. {
  23. get { return m_Kind; }
  24. }
  25. public override string ToString()
  26. {
  27. return "Name: " + m_Name + "[" + m_Kind.ToString() + "]";
  28. }
  29. }

本文標題:C#const常量詳細介紹
當(dāng)前地址:http://www.dlmjj.cn/article/dhdooss.html