C# 基础知识总结
要學(xué)好C#,基礎(chǔ)知識的重要性不言而喻,現(xiàn)將常用到的一些基礎(chǔ)進(jìn)行總結(jié),總結(jié)如下:
01. 數(shù)據(jù)類型轉(zhuǎn)換:
強(qiáng)制類型轉(zhuǎn)換(Chart--> int):
?char cr='A'; ??int i = (int)(cr);
02. 委托/匿名函數(shù)/Lamda表達(dá)式:
? ? 委托是匿名函數(shù)的起源,Lamda表達(dá)式又是匿名函數(shù)的升華。這些又是如何體現(xiàn)的呢,請看:
? ? 委托示例:
namespace Delegate {class Program{public delegate void TDelegate(int i, int j);static void Caculator(int i, int j){Console.WriteLine(i * j * i * j);}public static void InvokeDE(){TDelegate td = new TDelegate(Caculator);td.Invoke(3, 5);}static void Main(string[] args){InvokeDE();Console.ReadLine();}} } View Code? ? 匿名函數(shù)示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace CSP {class Program{public delegate void MyDelegate(int x, int y);static void Main(string[] args){MyDelegate md = delegate(int x, int y){Console.WriteLine(x + y);};md(10, 100);Console.ReadLine();}} } View Code? ?Lamda表達(dá)式(實(shí)際就是一個函數(shù))示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace CSP {class Program{private static void LamdaExpression(){int[] InitArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };int ResCount = InitArr.Where(n => n > 6).Count();Console.WriteLine(ResCount);}static void Main(string[] args){LamdaExpression();Console.ReadLine();}} } View Code03. 泛型Gereric:
? ??泛型是C#一個非常重要的用法,必須熟記于心:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace CSP {class Program{public static void GenericFunction(){int i = 10;string HI = "Hello World!";TestGC<int> tg_int = new TestGC<int>(i);TestGC<string> tg_string = new TestGC<string>(HI);Console.WriteLine(tg_int.t.ToString());Console.WriteLine(tg_string.t.ToString());}static void Main(string[] args){GenericFunction();Console.ReadLine();}}public class TestGC<T>{public T t;public TestGC(T t){this.t = t;}} } View Code04. ?虛方法Virtual:
? ? ?以前總覺得自己掌握的很好了,最近看了一些文章才對Virtual的執(zhí)行順序有了更深的理解,為了加深印象,我添加了示例圖并特地將本篇文章在此處進(jìn)行了引用:
class A {public virtual void Func() // 注意virtual,表明這是一個虛擬函數(shù) {Console.WriteLine("Func In A");} } class B : A // 注意B是從A類繼承,所以A是父類,B是子類 {public override void Func() // 注意override ,表明重新實(shí)現(xiàn)了虛函數(shù) {Console.WriteLine("Func In B");} } class C : B // 注意C是從B類繼承,所以B是父類,C是子類 { } class D : A // 注意D是從A類繼承,所以A是父類,D是子類 {public new void Func() // 注意new,表明覆蓋父類里的同名類,而不是重新實(shí)現(xiàn) {Console.WriteLine("Func In D");} } class E : D // 注意E是從D類繼承,所以D是父類,E是子類 {} class F : A {private new void Func() //注意new關(guān)鍵字前有private修飾符,故該隱藏只在F類內(nèi)有效 {Console.WriteLine("Func In F");}public void Func2() {Func(); //在F類內(nèi)隱藏了基類的Func方法,故此處調(diào)用的private new void Func() } }static void Main(string[] args) {A a; // 定義一個a這個A類的對象.這個A就是a的申明類 A b; // 定義一個b這個A類的對象.這個A就是b的申明類 A c; // 定義一個c這個A類的對象.這個A就是c的申明類 A d; // 定義一個d這個A類的對象.這個A就是d的申明類 A e; // 定義一個e這個A類的對象.這個A就是e的申明類 A f; // 定義一個f這個A類的對象.這個A就是f的申明類 a = new A(); // 實(shí)例化a對象,A是a的實(shí)例類 b = new B(); // 實(shí)例化b對象,B是b的實(shí)例類 c = new C(); // 實(shí)例化c對象,C是c的實(shí)例類 d = new D(); // 實(shí)例化d對象,D是d的實(shí)例類 e = new E(); // 實(shí)例化e對象,E是e的實(shí)例類f = new F(); // 實(shí)例化f對象,F是f的實(shí)例類Console.WriteLine("a.Func();");a.Func(); // 執(zhí)行a.Func:1.先檢查申明類A 2.檢查到是虛擬方法 3.轉(zhuǎn)去檢查實(shí)例類A,就為本身 4.執(zhí)行實(shí)例類A中的方法 5.輸出結(jié)果 Func In A Console.WriteLine("b.Func();");b.Func(); // 執(zhí)行b.Func:1.先檢查申明類A 2.檢查到是虛擬方法 3.轉(zhuǎn)去檢查實(shí)例類B,有重載的 4.執(zhí)行實(shí)例類B中的方法 5.輸出結(jié)果 Func In B Console.WriteLine("c.Func();");c.Func(); // 執(zhí)行c.Func:1.先檢查申明類A 2.檢查到是虛擬方法 3.轉(zhuǎn)去檢查實(shí)例類C,無重載的 4.轉(zhuǎn)去檢查類C的父類B,有重載的 5.執(zhí)行父類B中的Func方法 5.輸出結(jié)果 Func In B Console.WriteLine("d.Func();");d.Func(); // 執(zhí)行d.Func:1.先檢查申明類A 2.檢查到是虛擬方法 3.轉(zhuǎn)去檢查實(shí)例類D,無重載的(這個地方要注意了,雖然D里有實(shí)現(xiàn)Func(),但沒有使用override關(guān)鍵字,所以不會被認(rèn)為是重載) 4.轉(zhuǎn)去檢查類D的父類A,就為本身 5.執(zhí)行父類A中的Func方法 5.輸出結(jié)果 Func In A Console.WriteLine("e.Func();");e.Func(); // 執(zhí)行e.Func:E繼承D,E.Func沒有重寫父類中的方法,相當(dāng)于執(zhí)行父類D中的Func方法,輸出結(jié)果 Func In A Console.WriteLine("f.Func();");f.Func(); // 執(zhí)行f.Func:F類中雖然隱藏了基類中的Func方法,但是有private修飾符,該隱藏只在F類范圍內(nèi)有效。執(zhí)行f.Func相當(dāng)于執(zhí)行其基類中的Func方法,輸出結(jié)果 Func In A D d1 = new D();Console.WriteLine("d1.Func();");d1.Func(); // 執(zhí)行D類里的Func(),輸出結(jié)果 Func In D E e1 = new E();Console.WriteLine("e1.Func();");e1.Func(); // 執(zhí)行E類里的Func(),輸出結(jié)果 Func In D F f1 = new F();Console.WriteLine("f1.Func();");f1.Func(); // 執(zhí)行F類里的Func(),輸出結(jié)果 Func In AConsole.WriteLine("f1.Func2();");f1.Func2(); // 執(zhí)行F類里的Func2(),輸出結(jié)果 Func In F Console.ReadLine(); } View Code05. New和Override的用法:
? ? New是新建一個新方法,對舊方法進(jìn)行了屏蔽,而Override只是對父類中的方法進(jìn)行了覆蓋,具體詳細(xì)用法參見4. Virtual用法示例;
06.?foreach用法:
? ? foreach遍歷訪問的對象需要實(shí)現(xiàn)IEnumerable接口或聲明GetEnumerator方法的類型;
MSDN上的例子:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace CSP {public class Person{public string firstName;public string lastName;public Person(string fName, string lName){this.firstName = fName;this.lastName = lName;}}public class People : IEnumerable{private Person[] _people;public People(Person[] pArray){_people = new Person[pArray.Length];for (int i = 0; i < pArray.Length; i++){_people[i] = pArray[i];}}// Implementation for the GetEnumerator method. IEnumerator IEnumerable.GetEnumerator(){return (IEnumerator)GetEnumerator();}public PeopleEnum GetEnumerator(){return new PeopleEnum(_people);}}public class PeopleEnum : IEnumerator{public Person[] _people;int position = -1;public PeopleEnum(Person[] list){_people = list;}public bool MoveNext(){position++;return (position < _people.Length);}public void Reset(){position = -1;}object IEnumerator.Current{get{return Current;}}public Person Current{get{try{return _people[position];}catch (IndexOutOfRangeException){throw new InvalidOperationException();}}}}class App{static void Main(){Person[] peopleArray = new Person[3]{new Person("John", "Smith"),new Person("Jim", "Johnson"),new Person("Sue", "Rabon"),};People peopleList = new People(peopleArray);foreach (Person p in peopleList)Console.WriteLine(p.firstName + " " + p.lastName);Console.ReadLine();}} } View Code?下面例子是對上面的改動,只保留了對GetEnumerator()方法的實(shí)現(xiàn),移除了對IEnumerable接口和IEnumerator接口的繼承,執(zhí)行結(jié)果同上例一樣:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace CSP {public class Person{public string firstName;public string lastName;public Person(string fName, string lName){this.firstName = fName;this.lastName = lName;}}public class People{private Person[] _people;public People(Person[] pArray){_people = new Person[pArray.Length];for (int i = 0; i < pArray.Length; i++){_people[i] = pArray[i];}}public PeopleEnum GetEnumerator(){return new PeopleEnum(_people);}}public class PeopleEnum{public Person[] _people;int position = -1;public PeopleEnum(Person[] list){_people = list;}public bool MoveNext(){position++;return (position < _people.Length);}public Person Current{get{try{return _people[position];}catch (IndexOutOfRangeException){throw new InvalidOperationException();}}}}class App{static void Main(){Person[] peopleArray = new Person[3]{new Person("John", "Smith"),new Person("Jim", "Johnson"),new Person("Sue", "Rabon"),};People peopleList = new People(peopleArray);foreach (Person p in peopleList)Console.WriteLine(p.firstName + " " + p.lastName);Console.ReadLine();}} } View Code? ? PS.
A.實(shí)現(xiàn)實(shí)現(xiàn)IEnumerable接口的同時就必須實(shí)現(xiàn)IEnumerator接口;
? ? B.不一定要實(shí)現(xiàn)IEnumerable接口,但一定要實(shí)現(xiàn)GetEnumrator方法。
? ? 對于上述的功能,可以也嘗試使用語法糖(便捷寫法)C# yield來進(jìn)行實(shí)現(xiàn);
07.?靜態(tài)構(gòu)造函數(shù)
靜態(tài)構(gòu)造函數(shù),也稱靜態(tài)代碼塊,主要用于初始化靜態(tài)變量,示例如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace CSP {public class StaticBlock{public string Title;static StaticBlock(){Console.WriteLine("Here is the static block,only can be called for 1 time!");}public StaticBlock(string Title){this.Title = Title;}}class Program{static void Main(string[] args){StaticBlock sb_morning = new StaticBlock("Good morning!");Console.WriteLine(sb_morning.Title);StaticBlock sb_afternoon = new StaticBlock("Good afternoon!");Console.WriteLine(sb_afternoon.Title);Console.ReadLine();}} } View Code靜態(tài)構(gòu)造函數(shù)具有如下特點(diǎn)(來自網(wǎng)絡(luò)):
A.靜態(tài)構(gòu)造函數(shù)既無訪問修飾符亦無參數(shù);
? ? B.如果沒有編寫靜態(tài)構(gòu)造函數(shù),而這時類中包含帶有初始值設(shè)定的靜態(tài)字段,那么編譯器會自動生成默認(rèn)的靜態(tài)構(gòu)造函數(shù)。
? ? C.在創(chuàng)建第一個類實(shí)例或任何靜態(tài)成員被引用時,.NET將自動調(diào)用靜態(tài)構(gòu)造函數(shù)來初始化類,即無法直接調(diào)用與控制靜態(tài)構(gòu)造函數(shù)。
? ? D.如果類中包含用來開始執(zhí)行的 Main 方法,則該類的靜態(tài)構(gòu)造函數(shù)將在調(diào)用 Main 方法之前執(zhí)行。
? ? E.如果類中的靜態(tài)字段帶有初始化,則靜態(tài)字段的初始化語句將在靜態(tài)構(gòu)造函數(shù)之前運(yùn)行。
? ? F.一個類只能有一個靜態(tài)構(gòu)造函數(shù),不可以被繼承且最多只運(yùn)行一次。
08. 【反射】typeof/GetType
typeof:獲取類運(yùn)行時的類型及方法列表,參數(shù)只能為類名,用法typeof(類名);
? ??GetType:獲取類運(yùn)行時的類型及方法列表,由對象調(diào)用,用法:obj.GetType();
09.?where T : class
?主要用來對接口進(jìn)行限制,如下所示,限制接口IDataComponentBase<T>中的T必須為一個引用類型,如類,接口,數(shù)組;
public interface IDataComponentBase<T>?where T : class
10.?Guid對象賦值:
? ? Guid gd = new Guid("3a4f38a3-e064-e611-80d6-080027c84e1f");
11. Dispose():
? ??在使用using方法結(jié)束時會自動調(diào)用Dispose(),以便顯示釋放非托管資源(前提是該當(dāng)前類必須實(shí)現(xiàn)接口:IDisposable);
12. 保留兩位小數(shù):
? ? ? Decimal?OVNum,NCNum;
? ? ? ... ...
? ? ? Decimal TotNum = OVNum + NCNum;
? ? ? Decimal d = NCNum * 100 / TotNum;
? ? ? e.Result = Decimal.Round(d, 2);
13. 利用List自帶的Sort進(jìn)行排序:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace CA {class Program{static void Main(string[] args){List<Light> lts = new List<Light>();Light lt0 = new Light();lt0.LTypeName = "Filament";lt0.W = 12;Light lt1 = new Light();lt1.LTypeName = "Common";lt1.W = 25;Light lt2 = new Light();lt2.LTypeName = "Efficient";lt2.W = 50;lts.Add(lt0);lts.Add(lt1);lts.Add(lt2);Console.WriteLine("Before sort:");foreach (Light l in lts){Console.WriteLine(l.LTypeName+":"+l.W);}//A~Z//lts.Sort((x, y) => x.LTypeName.CompareTo(y.LTypeName));//Z~Alts.Sort((x, y) => -x.LTypeName.CompareTo(y.LTypeName));Console.WriteLine("After sort:");foreach (Light l in lts){Console.WriteLine(l.LTypeName + ":" + l.W);}Console.ReadLine();}}public class Light{public string LTypeName { get; set; }public int W { get; set; }} } View Code14.?數(shù)組,ArrayList,List的區(qū)別:
數(shù)組的優(yōu)點(diǎn)是可以存儲多個維度的記錄,且連續(xù)存放,缺點(diǎn)是需要在定義時指定數(shù)組的長度,且定義好后不能擴(kuò)展;
? ? ?ArrayList在定義時不需要指定長度也不需要定義存入的數(shù)據(jù)的數(shù)據(jù)類型,可以自由擴(kuò)展。所以ArrayList可以存放不同類型的數(shù)據(jù)(以object存入,要進(jìn)行裝箱操作)到ArrayList,所以ArrayList為非類型安全的;
? ? ?使用如下所示:
ArrayList al = new ArrayList();
al.Add(100);
al.Add("Hello");
?List與ArrayList一樣,在定義時不需要指定長度,可以自由擴(kuò)展。同時,在聲明List時,需要定義存入的數(shù)據(jù)的數(shù)據(jù)類型,實(shí)現(xiàn)了類型安全;
?ArrayList的命名空間:System.Collections.ArrayList
? ? ?List的命名空間:System.Collections.Generic.List
15. const/readonly
用const聲明的常量為編譯時常量,readonly聲明的常量為運(yùn)行時常量; 16. 協(xié)變/逆變 在使用泛型的場合,把子類的引用賦給父類,參見該文章;關(guān)于C#還有更多內(nèi)容需要研究,希望自己能再接再厲,繼續(xù)總結(jié)!
?
轉(zhuǎn)載于:https://www.cnblogs.com/sccd/p/5418326.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
- 上一篇: vijos p1460——拉力赛
- 下一篇: 010-python基础-数据类型-字符