C#資料(一)
1.靜態成員和非靜態成員的區別?
答:
靜態變數使用 static 修飾符進行宣告,在類被例項化時建立,通過類進行訪問不帶有 static 修飾符宣告的變數稱做非靜態變數,在物件被例項化時建立,通過物件進行訪問一個類的所有例項的同一靜態變數都是同一個值,同一個類的不同例項的同一非靜態變數可以是不同的值靜態函式的實現裡不能使用非靜態成員,如非靜態變數、非靜態函式等
示例:
using System;
using ric;
using ;
namespace Example01
{
class Program
{
class Class1
{
public static String staticStr = "Class";
public String notstaticStr = "Obj";
}
static void Main(string[] args)
{
//靜態變數通過類進行訪問,該類所有例項的同一靜態變數都是同一個值
eLine("Class1's staticStr: {0}", icStr);
Class1 tmpObj1 = new Class1();
taticStr = "tmpObj1";
Class1 tmpObj2 = new Class1();
taticStr = "tmpObj2";
//非靜態變數通過物件進行訪問,不同物件的同一非靜態變數可以有不同的值
eLine("tmpObj1's notstaticStr: {0}", taticStr);
eLine("tmpObj2's notstaticStr: {0}", taticStr);
Line();
}
}
}
結果:
Class1's staticStr: Class
tmpObj1's notstaticStr: tmpObj1
tmpObj2's notstaticStr: tmpObj2
t 和 static readonly 區別?
答:const
用 const 修飾符宣告的成員叫常量,是在編譯期初始化並嵌入到客戶端程式
static readonly
用 static readonly 修飾符宣告的成員依然是變數,只不過具有和常量類似的使用方法:通過類進行訪問、初始化後不可以修改。但與常量不同的是這種變數是在執行期初始化
示例:
測試類:
using System;
using ric;
using ;
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 ric;
using ;
using Example02Lib;
namespace Example02
{
class Program
{
static void Main(string[] args)
{
//修改Example02中Class1的strConst初始值後,只編譯Example02Lib專案
//然後到資源管理器裡把新編譯的拷貝所在的目錄,
執行
//切不可在IDE裡直接除錯執行因為這會重新編譯整個解決方案!!
//可以看到strConst的輸出沒有改變,而strStaticReadonly的輸出已經改變
//表明Const變數是在編譯期初始化並嵌入到客戶端程式,而StaticReadonly是在執行時初始化的
eLine("strConst : {0}", onst);
eLine("strStaticReadonly : {0}", taticReadonly);
Line();
}
}
}
結果:
strConst : Const
strStaticReadonly : StaticReadonly
修改後的示例:
測試類:
using System;
using ric;
using ;
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";
}
}
結果
strConst : Const
strStaticReadonly : StaticReadonly Changed
rn 是什麼意思?
答:extern 修飾符用於宣告由程式集外部實現的成員函式經常用於系統API函式的呼叫(通過 DllImport )。注意,和DllImport一起使用時要加上 static 修飾符也可以用於對於同一程式集不同版本元件的呼叫(用 extern 宣告別名)不能與 abstract 修飾符同時使用
示例:
using System;
using ric;
using ;
using ropServices;
namespace Example03
{
class Program
{
//注意DllImport是一個Attribute Property,在ropServices名稱空間中定義
//extern與DllImport一起使用時必須再加上一個static修飾符
[DllImport("")]
public static extern int MessageBox(int Handle, string Message,
string Caption, int Type);
static int Main()
{
string myString;
e("Enter your message: ");
myString = Line();
return MessageBox(0, myString, "My Message Box", 0);