C# 基礎之const


1、使用 const 關鍵字來聲明某個常量字段或常量局部變量。常量字段和常量局部變量不是變量並且不能修改。 常量可以為數字、布爾值、字符串或 null 引用(Constants can be numbers, Boolean values, strings, or a null reference)。

下面代碼會報編譯錯誤:

public const DateTime myDateTime = new DateTime(2018,05,23,0,0,0);

 

 

2、不允許在常數聲明中使用 static 修飾符。

  static const string a = "a";  //Error

報錯:不能將變量“a”標記為static。

3、常數可以參與常數表達式,如下所示:

public const int c1 = 5;  
public const int c2 = c1 + 100;

4、readonly 關鍵字與 const 關鍵字不同:const 字段只能在該字段的聲明中初始化。readonly字段可以在聲明或構造函數中初始化。因此,根據所使用的構造函數,`readonly` 字段可能具有不同的值。

 

 1  class ReadOnly
 2     {
 3         private readonly string str;
 4         public ReadOnly()
 5         {
 6             str = @"ReadOnly() 構造函數";
 7             Console.WriteLine(str);
 8         }
 9         public ReadOnly(int i)
10             : this()
11         {
12             str = @"ReadOnly(int i) 構造函數";
13             Console.WriteLine(str);
14             str = @"asd";
15             Console.WriteLine(str);
16         }
17      }
ReadOnly 構造函數初始化字符串

調用:     ReadOnly ro = new ReadOnly(1);

輸出:

 5、static 

如果 static 關鍵字應用於類,則類的所有成員都必須是靜態的。不能通過實例引用靜態成員。 然而,可以通過類型名稱引用它。

public class MyBaseC
{
    public struct MyStruct
    {
        public static int x = 100;
    }
}

若要引用靜態成員 x,除非可從相同范圍訪問該成員,否則請使用完全限定的名稱 MyBaseC.MyStruct.x。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM