C#基礎(chǔ)概念學(xué)習(xí)總結(jié)
C#基礎(chǔ)概念之一,靜態(tài)變量和非靜態(tài)變量的區(qū)別?
靜態(tài)變量:
靜態(tài)變量使用 static 修飾符進(jìn)行聲明,在所屬類被裝載時創(chuàng)建,通過類進(jìn)行訪問,所屬類的所有實(shí)例的同一靜態(tài)變量都是同一個值
非靜態(tài)變量:
不帶有 static 修飾符聲明的變量稱做非靜態(tài)變量,在類被實(shí)例化時創(chuàng)建,通過對象進(jìn)行訪問,同一個類的不同實(shí)例的同一非靜態(tài)變量可以是不同的值
示例:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Example01 {
- class Program {
- class Class1 {
- public static String staticStr = "Class";public String notstaticStr = "Obj";
- }
- static void Main(string[] args)
- {
- //靜態(tài)變量通過類進(jìn)行訪問,該類所有實(shí)例的同一靜態(tài)變量都是同一個值
- Console.WriteLine("Class1's staticStr: {0}", Class1.staticStr);
- Class1 tmpObj1 = new Class1();
- tmpObj1.notstaticStr = "tmpObj1";
- Class1 tmpObj2 = new Class1();
- tmpObj2.notstaticStr = "tmpObj2";
- //非靜態(tài)變量通過對象進(jìn)行訪問,不同對象的同一非靜態(tài)變量可以有不同的值
- Console.WriteLine("tmpObj1's notstaticStr: {0}", tmpObj1.notstaticStr);
- Console.WriteLine("tmpObj2's notstaticStr: {0}", tmpObj2.notstaticStr);
- Console.ReadLine();
- }
C#基礎(chǔ)概念之二,const 和 static readonly 區(qū)別?
const
用 const 修飾符聲明的成員叫常量,是在編譯期初始化并嵌入到客戶端程序
static readonly
用 static readonly 修飾符聲明的成員依然是變量,只不過具有和常量類似的使用方法:通過類進(jìn)行訪問、初始化后不可以修改。但與常量不同的是這種變量是在運(yùn)行期初始化
示例:
測試類:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Example02Lib {
- public class Class1 {
- public const String strConst = "Const";
- public static readonly String strStaticReadonly = "StaticReadonly";
- public const String strConst = "Const Changed";
- public static readonly String strStaticReadonly = "StaticReadonly Changed";
- }
客戶端代碼:
- using System;
- using System.Collections.Generic;
- using System.Text;
- using Example02Lib;
- namespace Example02 {
- class Program {
- static void Main(string[] args)
- {
- //修改Example02中Class1的strConst初始值后,只編譯Example02Lib項(xiàng)目
- //然后到資源管理器里把新編譯的 Example02Lib.dll拷貝Example02.exe所在的目錄,
執(zhí)行Example02.exe- //切不可在IDE里直接調(diào)試運(yùn)行因?yàn)檫@會重新編譯整個解決方案??!
- //可以看到strConst的輸出沒有改變,而strStaticReadonly的輸出已經(jīng)改變/
- /表明Const變量是在編譯期初始化并嵌入到客戶端程序,而StaticReadonly是在運(yùn)行時初始化的
- Console.WriteLine("strConst : {0}", Class1.strConst);
- Console.WriteLine("strStaticReadonly : {0}", Class1.strStaticReadonly);
- Console.ReadLine();
- }
修改后的示例:
測試類:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Example02Lib {
- public class Class1 {
- //public const String strConst = "Const";
- //public static readonly String strStaticReadonly = "StaticReadonly";
- public const String strConst = "Const Changed";
- public static readonly String strStaticReadonly = "StaticReadonly Changed";
- }
以上介紹兩點(diǎn)C#基礎(chǔ)概念
【編輯推薦】