C# 基礎知識總結


要學好C#,基礎知識的重要性不言而喻,現將常用到的一些基礎進行總結,總結如下:

01. 數據類型轉換

  強制類型轉換(Chart--> int):

  char cr='A';   int i = (int)(cr);

02. 委托/匿名函數/Lamda表達式:

    委托是匿名函數的起源,Lamda表達式又是匿名函數的升華。這些又是如何體現的呢,請看:

    委托示例:

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

    匿名函數示例:

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表達式(實際就是一個函數)示例:

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 Code

03. 泛型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 Code

04.  虛方法Virtual:

     以前總覺得自己掌握的很好了,最近看了一些文章才對Virtual的執行順序有了更深的理解,為了加深印象,我添加了示例圖並特地將本篇文在此處進行了引用:

class A
{
    public virtual void Func() // 注意virtual,表明這是一個虛擬函數 
    {
        Console.WriteLine("Func In A");
    }
}
class B : A // 注意B是從A類繼承,所以A是父類,B是子類 
{
    public override void Func() // 注意override ,表明重新實現了虛函數 
    {
        Console.WriteLine("Func In B");
    }
}
class C : B // 注意C是從B類繼承,所以B是父類,C是子類 
{
}
class D : A // 注意D是從A類繼承,所以A是父類,D是子類 
{
    public new void Func() // 注意new,表明覆蓋父類里的同名類,而不是重新實現 
    {
        Console.WriteLine("Func In D");
    }
}
class E : D // 注意E是從D類繼承,所以D是父類,E是子類 
{
  
}
class F : A
{
    private new void Func() //注意new關鍵字前有private修飾符,故該隱藏只在F類內有效
    {
        Console.WriteLine("Func In F");
    }

    public void Func2() 
    {
        Func(); //在F類內隱藏了基類的Func方法,故此處調用的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(); // 實例化a對象,A是a的實例類 
    b = new B(); // 實例化b對象,B是b的實例類 
    c = new C(); // 實例化c對象,C是c的實例類 
    d = new D(); // 實例化d對象,D是d的實例類 
    e = new E(); // 實例化e對象,E是e的實例類
    f = new F(); // 實例化f對象,F是f的實例類
    Console.WriteLine("a.Func();");
    a.Func(); // 執行a.Func:1.先檢查申明類A 2.檢查到是虛擬方法 3.轉去檢查實例類A,就為本身 4.執行實例類A中的方法 5.輸出結果 Func In A 
    Console.WriteLine("b.Func();");
    b.Func(); // 執行b.Func:1.先檢查申明類A 2.檢查到是虛擬方法 3.轉去檢查實例類B,有重載的 4.執行實例類B中的方法 5.輸出結果 Func In B 
    Console.WriteLine("c.Func();");
    c.Func(); // 執行c.Func:1.先檢查申明類A 2.檢查到是虛擬方法 3.轉去檢查實例類C,無重載的 4.轉去檢查類C的父類B,有重載的 5.執行父類B中的Func方法 5.輸出結果 Func In B 
    Console.WriteLine("d.Func();");
    d.Func(); // 執行d.Func:1.先檢查申明類A 2.檢查到是虛擬方法 3.轉去檢查實例類D,無重載的(這個地方要注意了,雖然D里有實現Func(),但沒有使用override關鍵字,所以不會被認為是重載) 4.轉去檢查類D的父類A,就為本身 5.執行父類A中的Func方法 5.輸出結果 Func In A 
    Console.WriteLine("e.Func();");
    e.Func(); // 執行e.Func:E繼承D,E.Func沒有重寫父類中的方法,相當於執行父類D中的Func方法,輸出結果 Func In A 
    Console.WriteLine("f.Func();");
    f.Func(); // 執行f.Func:F類中雖然隱藏了基類中的Func方法,但是有private修飾符,該隱藏只在F類范圍內有效。執行f.Func相當於執行其基類中的Func方法,輸出結果 Func In A 
    
    D d1 = new D();
    Console.WriteLine("d1.Func();");
    d1.Func(); // 執行D類里的Func(),輸出結果 Func In D 

    E e1 = new E();
    Console.WriteLine("e1.Func();");
    e1.Func(); // 執行E類里的Func(),輸出結果 Func In D

    F f1 = new F();
    Console.WriteLine("f1.Func();");
    f1.Func(); // 執行F類里的Func(),輸出結果 Func In A
    Console.WriteLine("f1.Func2();");
    f1.Func2(); // 執行F類里的Func2(),輸出結果 Func In F
   
    Console.ReadLine();
}
View Code

05. New和Override的用法:

    New是新建一個新方法,對舊方法進行了屏蔽,而Override只是對父類中的方法進行了覆蓋,具體詳細用法參見4. Virtual用法示例;

06. foreach用法

    foreach遍歷訪問的對象需要實現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()方法的實現,移除了對IEnumerable接口和IEnumerator接口的繼承,執行結果同上例一樣:

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.實現實現IEnumerable接口的同時就必須實現IEnumerator接口;

    B.不一定要實現IEnumerable接口,但一定要實現GetEnumrator方法

    對於上述的功能,可以也嘗試使用語法糖(便捷寫法)C# yield來進行實現;

07. 靜態構造函數

  靜態構造函數,也稱靜態代碼塊,主要用於初始化靜態變量,示例如下:

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

  靜態構造函數具有如下特點(來自網絡):

  A.靜態構造函數既無訪問修飾符亦無參數;

    B.如果沒有編寫靜態構造函數,而這時類中包含帶有初始值設定的靜態字段,那么編譯器會自動生成默認的靜態構造函數

    C.在創建第一個類實例或任何靜態成員被引用時,.NET將自動調用靜態構造函數來初始化類,即無法直接調用與控制靜態構造函數。

    D.如果類中包含用來開始執行的 Main 方法,則該類的靜態構造函數將在調用 Main 方法之前執行

    E.如果類中的靜態字段帶有初始化,則靜態字段的初始化語句將在靜態構造函數之前運行。

    F.一個類只能有一個靜態構造函數,不可以被繼承且最多只運行一次

08. 反射typeof/GetType

  typeof:獲取類運行時的類型方法列表,參數只能為類名,用法typeof(類名);

    GetType:獲取類運行時的類型方法列表,由對象調用,用法:obj.GetType();

09. where T : class

   主要用來對接口進行限制,如下所示,限制接口IDataComponentBase<T>中的T必須為一個引用類型,如類,接口,數組;

  public interface IDataComponentBase<T> where T : class

10. Guid對象賦值:

    Guid gd = new Guid("3a4f38a3-e064-e611-80d6-080027c84e1f");

11. Dispose():

    在使用using方法結束時會自動調用Dispose(),以便顯示釋放非托管資源(前提是該當前類必須實現接口:IDisposable);

12. 保留兩位小數:

      Decimal OVNum,NCNum;

      ... ...

      Decimal TotNum = OVNum + NCNum;
      Decimal d = NCNum * 100 / TotNum;
      e.Result = Decimal.Round(d, 2);

13. 利用List自帶的Sort進行排序:

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~A
            lts.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 Code

14. 數組,ArrayList,List的區別:

  數組的優點是可以存儲多個維度的記錄,且連續存放,缺點是需要在定義時指定數組的長度,且定義好后不能擴展;

     ArrayList在定義時不需要指定長度不需要定義存入的數據的數據類型,可以自由擴展。所以ArrayList可以存放不同類型的數據(以object存入,要進行裝箱操作)到ArrayList,所以ArrayList為非類型安全的;

     使用如下所示:

  ArrayList al = new ArrayList();

  al.Add(100);

  al.Add("Hello");

   List與ArrayList一樣,在定義時不需要指定長度,可以自由擴展。同時,在聲明List時,需要定義存入的數據的數據類型,實現了類型安全;

   ArrayList的命名空間:System.Collections.ArrayList

     List的命名空間:System.Collections.Generic.List

15. const/readonly

      用const聲明的常量為編譯時常量,readonly聲明的常量為運行時常量;
 
16. 協變/逆變
  
  在使用泛型的場合,把子類的引用賦給父類,參見該 文章

  關於C#還有更多內容需要研究,希望自己能再接再厲,繼續總結!

 


免責聲明!

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



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