#region 常量和静态变量静态类readonly
生活随笔
收集整理的這篇文章主要介紹了
#region 常量和静态变量静态类readonly
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#region 常量和靜態變量靜態類readonly
#region 常量和靜態變量靜態類readonly//----------------------------------------------------------------------//常量和靜態變量,靜態類//----------------------------------------------------------------------//類的靜態變量和常量,都屬于類而不屬于對象,不能用對象來調用,只能用類名調用//這不同于C++,是更合理的設計//常量的值在類定義時就確定了,不因對象而不同,因此存放在類中更合理class CNormclass{class CInclass{public float fx = 20;}public int _id;public const string cname = "CNormalclass";//1,常量僅能修飾 :數字,bool,字符串,null引用//不能像C++那樣定義一個常量對象,這真是太悲哀了,因為很多時候這可以加速數據傳遞,增加安全性//由于這個原因,C#的List.ToArray每次都只能返回一個內部數組的拷貝,因此使用list存儲數量較大較復雜的數據時//不要輕易使用ToArray,直接用List就行了,它也支持下標索引方式取數組元素const CInclass lst = null;//2,readonly也不能實現常量對象的效果//readonly僅表示變量本身不能被賦值,但不阻止通過對象變量更改對象內的字段//onc.readonlyobj.fx = 20public float fx = 20;private readonly CInclass readonlyobj = new CInclass();public static void Test(){//1,不能調用非靜態字段或方法//this._id = 20; //error,沒有this指針//2,可以調用常量字段var lname = cname;var onc = new CNormclass();//私有變量在類的靜態方法也可以訪問//2,雖然不能更改readonlyobj本身的值,卻可以更改其內部成員的值,這就是readonly的作用onc.readonlyobj.fx = 20; }}static class C712//類中類,默認為私有{//靜態類不能實例化,且只能聲明:常量,靜態常量,靜態屬性,靜態方法public const int constX = 20; //1,常量public static int staticX = 0; //2,靜態常量public static int ix { set; get; } //3,靜態屬性//一,【靜態類中不能定義實例化字段】//public int _id; //二,【靜態類中不能定義實例化字段】//void Ctest(){ //【error: 靜態類中不能定義實例化方法】// this._id = 20;//}static void Test()//4,靜態方法 {//三,【靜態方法中不能調用非靜態變量或方法,因為沒有this指針】//_id = 20; //error //四,【可以調用常量字段,這與C++不同】var c = constX;}}public const int ixd = 20;public static float fx = 20;public void Testff(){fx = 30; //等價于Program.fx = 30,而不是 this.fx = 30;Program.fx = 30;var tx = C712.constX;C712.staticX = 30;var ix = Program.ixd;//var oc7 = new C712(); //error 靜態類不能創建實例}?
posted on 2018-07-30 16:52 時空觀察者9號 閱讀(...) 評論(...) 編輯 收藏
總結
以上是生活随笔為你收集整理的#region 常量和静态变量静态类readonly的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: //todo 的用处
- 下一篇: C# 全总结