三天學(xué)完C#--第二天

結(jié)構(gòu)體

結(jié)構(gòu)體與類基本一致,但是不同的地方在于,結(jié)構(gòu)體在棧上開辟空間,而類在堆上開辟空間.所以結(jié)構(gòu)體是值類型而類是引用類型。還有就是結(jié)構(gòu)體里不允許寫無參構(gòu)造必須寫有參構(gòu)造,但是可以寫無參靜態(tài)構(gòu)造。結(jié)構(gòu)體中不允許寫析構(gòu)代碼。結(jié)構(gòu)體只有一個父類object,不能被其他結(jié)構(gòu)體或類繼承,也不能繼承自其他結(jié)構(gòu)體或類。

clipboard.png
clipboard1.png

語法如下:

靜態(tài)類

image

靜態(tài)類不能創(chuàng)建實實例對象,不能聲明實例成員(實例變量,實例方法),只能聲明靜態(tài)方法,靜態(tài)變量,靜態(tài)構(gòu)造方法,靜態(tài)類只能有一個父類object。靜態(tài)類一般用于設(shè)計工具類。

Sealed修飾符

sealed修飾的類不能被繼承。sealed修飾的方法不能被重修(但至少被重寫一次),

算數(shù)運算符重載

程序語言可以使用 關(guān)鍵字operator 根據(jù)需要對算數(shù)運算符進行重載,實現(xiàn)其他的功能。關(guān)系運算符全部可以重載,但是要成對重載。比如重載了> 必須重載 < ,重載了>= 必須重載 <= 等 。邏輯運算符中 && || 不能重載。 位運算符 ~可以被重載

image

注意:方法必須聲明被 static,public 修飾,并且只能重載一元運算符(操作一個數(shù)字的運算符 與(&) 或(|) 非(!) 負號- 正號 + )

抽象類

用關(guān)鍵字修飾 abstract 的類,不能實例化對象。用關(guān)鍵字修飾 abstract 的方法沒有方法體,C#與JAVA中的抽象方法完全一致。只不過C#重寫父類方法是使用override修飾,而JAVA中不需要,最多可以選擇加@override 注解。

image

接口

C#中的接口除了在實現(xiàn)接口的時候用 冒號 實現(xiàn) 以外,其他的大部分特性與JAVA完全一致。并且既有繼承又有實現(xiàn)接口的時候,父類在第一位,其次在后面。

image
image
image

向上轉(zhuǎn)型

image

C#與java 的接口不一樣的地方有:C#接口中可以聲明屬性并寫屬性訪問器,而JAVA中不行.C#中的繼承可以是多繼承,而JAVA中就不行。

命名空間

1,C#中的命名空間相當于JAVA中的Pakage,里面的成員只能存放類,方法,結(jié)構(gòu)體,接口等類型

2,命名空間可以嵌套使用,并且命名空間如果和類的名字相同時應(yīng)該 namespace.class 這種格式引用類。

3,使用 using xxxx; 來引用命名空間,如果多個命名空間名字一樣,則說明他們是一個命名空間的

image
image

委托

C# 里面有一種方法類型叫做委托

實例化 一個委托對象 需要用一個方法來實例化

這個方法的返回值類型和參數(shù)列表也保持一致

image

第二種寫法

image

在這里testDelegate 指向了一個方法,可以直接使用。

image
image

組合委托(多播委托),可以使用運算符 + 來組合兩個委托

image
image

這樣就簡潔了代碼

也可以使用 - 號來解除委托

image
image
image

匿名方法委托寫法如下:

image

C#的 lamda表達式寫法如下:

image

一種熟悉的感覺,因為JAVA的lamda表達式也是這樣寫的,如果多寫lamda表達式可以使更多程序員看懂。并且也能提高程序的運行效率

委托回調(diào)

當有一個需求是當下載器下載完成后通知用戶下載完成,首先知道下載任務(wù)進度的是下載器自己,然后就是要通過記錄用戶,下載完成后就通知該用戶。這一系列操作用到了設(shè)計模式--委托。代碼如下:

image
image
image
image

以上代碼存在擴展性問題,因此用delegate 優(yōu)化

using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
namespace ConsoleApp1{
    class DownloadTool

    {

        public DownloadComplete downloadComplete;

        //下載數(shù)據(jù)

        public void DownloadData(string url,string username)

        {

            //模擬數(shù)據(jù)下載

            for (int i = 0; i <= 100; i += 5)

            {

                //線程休眠:讓程序休眠50毫秒

                Thread.Sleep(10);

                //清屏

                Console.Clear();

                Console.WriteLine($"數(shù)據(jù)下載中......({i})");

            }

            Console.WriteLine("恭喜  " + username + "  您的數(shù)據(jù)下載完成!");

            downloadComplete("hello world!");

        }

    }

    class Person {

        string username;

        public string Username{

            get{  return this.username;}

              }

        public Person(string username) {

            this.username = username;

            Console.WriteLine(username);

        }

        public void DownloadData(String url) {

            DownloadTool downloadTool = new DownloadTool();

            downloadTool.downloadComplete = DealWithDownloadData;

            downloadTool.DownloadData(url,"小張");

        }

        public void DealWithDownloadData(String result)

        {

            ConsoleColor originalColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine(result);

            Console.ForegroundColor = originalColor;

        }

    }

    delegate void DownloadComplete(string result);

    class Program

    {

      //下載工具類(模擬迅雷等下載工具)

        static void Main(string[] args)

        {

            Person person = new Person("小明");

            person.DownloadData("www.baidu.com");

        }

訂閱/發(fā)布(觀察者)模式

思想:將一組操作封裝起來,不關(guān)心訂閱者是誰,只要實現(xiàn)了這個接口的訂閱者,就會接收到發(fā)布的消息(執(zhí)行的操作)

using System;
using System.Collections.Generic;
using System.Timers;
namespace ConsoleApp1

{

    class Program

    {

        interface INewspaper {

            void SetNewspaper(Newspaper newspaper);

            void ReadNewspaper();

        }

        class Company:INewspaper

        {

            public string Name { get; set; }

            public Company(string name) { this.Name = name; }

            public Newspaper Newspaper { get; set; }

            public void SetNewspaper(Newspaper newspaper)

            {

                this.Newspaper = newspaper;

            }

            public void ReadNewspaper()

            {

                Console.WriteLine("公司{0}正在讀報紙 {1}標題是 {2} 出版社{3}", this.Name, this.Newspaper.Title, this.Newspaper.Content, this.Newspaper.PublisherName);

            }

        }

            class Person : INewspaper {

            public string Name { get; set; }

            public Person(string name) { this.Name = name; }

            public Newspaper Newspaper { get; set; }

            public void SetNewspaper(Newspaper newspaper) {

                this.Newspaper = newspaper; }

            public void ReadNewspaper() {

                Console.WriteLine("{0}正在讀報紙 {1}標題是 {2}  出版社{3}", this.Name,this.Newspaper.Title, this.Newspaper.Content,this.Newspaper.PublisherName);

            }

        }

        class Newspaper {

        string title;

        string content;

        public string PublisherName { get; set; }

        public string Title { get; set; }

        public string Content { get; set; }

        }

        class Publisher {

            public string Name { get; set;}

          public Publisher(string name) {

                this.Name = name;

            }

            public List<INewspaper> subscribers = new List<INewspaper>();

            public void SendNewspaper(Newspaper newspaper) {

                newspaper.PublisherName = this.Name;

                subscribers.ForEach(subscriber => { subscriber.SetNewspaper(newspaper); subscriber.ReadNewspaper(); });

            }

        }

        static void Main(string[] args)

        {

            var publisher = new Publisher("出版社X");

            publisher.subscribers.Add(new Person("a"));

            publisher.subscribers.Add(new Person("b"));

            publisher.subscribers.Add(new Person("c"));

            publisher.subscribers.Add(new Company("a"));

            publisher.subscribers.Add(new Company("b"));

            publisher.subscribers.Add(new Company("c"));

            publisher.SendNewspaper(new Newspaper() { Title="標題",Content="內(nèi)容" });

            }

        }

}

C#方式的訂閱/發(fā)布模式

using System;

using System.Collections.Generic;

using System.Timers;

namespace ConsoleApp1

{

    class Program

    {

        class Company

        {

            public string Name { get; set; }

            public Company(string name) { this.Name = name; }

            public Newspaper Newspaper { get; set; }

            public void SetNewspaper(Newspaper newspaper)

            {

                this.Newspaper = newspaper;

            }

            public void ReadNewspaper()

            {

                Console.WriteLine("公司{0}正在讀報紙 {1}標題是 {2} 出版社{3}", this.Name, this.Newspaper.Title, this.Newspaper.Content, this.Newspaper.PublisherName);

            }

        }

            class Person {

            public string Name { get; set; }

            public Person(string name) { this.Name = name; }

            public Newspaper Newspaper { get; set; }

            public void SetNewspaper(Newspaper newspaper) {

                this.Newspaper = newspaper; }

            public void ReadNewspaper() {

                Console.WriteLine("{0}正在讀報紙 {1}標題是 {2}  出版社{3}", this.Name,this.Newspaper.Title, this.Newspaper.Content,this.Newspaper.PublisherName);

            }

        }

        class Newspaper {

        string title;

        string content;

        public string PublisherName { get; set; }

        public string Title { get; set; }

        public string Content { get; set; }

        }

        class Publisher {

            public string Name { get; set; }

            public Publisher(string name) {

                this.Name = name;

            }

            /*

            *

            *

            * 

            * //聲明委托

            * public delegate void _Subscribers(Newspaper newspaper);

            * //委托屬性

            * public _Subscribers Subscribers { get;set;}

            *

            * */

            // 委托 Action 簡化

            public Action<Newspaper> Subscribers;

            //發(fā)布,通知,廣播

          public void SendNewspaper(Newspaper newspaper) {

                newspaper.PublisherName = this.Name;

                Subscribers(newspaper);

            }

        }

        static void Main(string[] args)

        {

            var publisher = new Publisher("出版社X");

            Person Aperson = new Person("A");

            Person Bperson = new Person("B");

            Company companyA = new Company("CompanyA");

            Company companyB = new Company("CompanyB");

            publisher.Subscribers = Aperson.SetNewspaper;//訂閱,注冊

            publisher.Subscribers -= Aperson.SetNewspaper;//退訂,取消注冊

            publisher.Subscribers += Bperson.SetNewspaper;//委托鏈

            publisher.Subscribers += companyA.SetNewspaper;

            publisher.Subscribers += companyB.SetNewspaper;

            publisher.SendNewspaper(new Newspaper() { Title="標題",Content="內(nèi)容" });

            companyA.ReadNewspaper(); } }   

}

C#中的Event來優(yōu)化以上程序存在的BUG

事件

在C#中通過事件來描述對象或類間的動作協(xié)調(diào)和信息傳遞,在JAVA中也存在這一機制(swing,AWT,Android 等客戶端編程),只不過JAVA中的事件都是通過接口實現(xiàn)而沒有委托這種數(shù)據(jù)類型。

事件模型的五個組成部分

1,事件的擁有者(event source,對象)

2, 事件成員(event,成員)

3,事件的響應(yīng)者(event subscriber,對象)

4,事件處理器(event handler,成員)-------本質(zhì)上是一個回調(diào)方法

5,事件訂閱--把事件處理器與事件關(guān)聯(lián)在一起,本質(zhì)上是一種以委托類型 為基礎(chǔ)的“約定”

using System;

using System.Collections.Generic;

using System.Timers;

namespace ConsoleApp1

{

    class Program

    {

        class PublisherArgs : System.EventArgs {

            public PublisherArgs(Newspaper newspaper) {

                this.Newspaper = newspaper;

            }

            public Newspaper Newspaper { get; set;}

        }

        class Company

        {

            public string Name { get; set; }

            public Company(string name) { this.Name = name; }

            public Newspaper Newspaper { get; set; }

            public void SetNewspaper(object sender, PublisherArgs publisherArgs)

            {

                if (sender is Publisher)

                {

                    publisherArgs.Newspaper.PublisherName = (sender as Publisher).Name;

                }

                this.Newspaper = publisherArgs.Newspaper;

            }

            public void ReadNewspaper()

            {

                Console.WriteLine("公司{0}正在讀報紙 {1}標題是 {2} 出版社{3}", this.Name, this.Newspaper.Title, this.Newspaper.Content, this.Newspaper.PublisherName);

            }

        }

            class Person {

            public string Name { get; set; }

            public Person(string name) { this.Name = name; }

            public Newspaper Newspaper { get; set; }

            public void SetNewspaper(object sender, PublisherArgs publisherArgs) {

                if (sender is Publisher) {

                    publisherArgs.Newspaper.PublisherName = (sender as Publisher).Name;

                }

                this.Newspaper = publisherArgs.Newspaper;

            }

            public void ReadNewspaper() {

                Console.WriteLine("{0}正在讀報紙 {1}標題是 {2}  出版社{3}", this.Name,this.Newspaper.Title, this.Newspaper.Content,this.Newspaper.PublisherName);

            }

        }

        class Newspaper {

        string title;

        string content;

        public string PublisherName { get; set; }

        public string Title { get; set; }

        public string Content { get; set; }

        }

        class Publisher {

            public string Name { get; set; }

            public Publisher(string name) {

                this.Name = name;

            }

            /*

            *

            *

            * 

            * //聲明委托

            * public delegate void _Subscribers(Newspaper newspaper);

            * //委托屬性

            * public _Subscribers Subscribers { get;set;}

            *

            * */

            // 委托 Action 簡化

            //public event Action<object,Newspaper> Subscribers=null;

            //EventHandler  事件處理器

            public event EventHandler<PublisherArgs> Subscribers = null;

            //發(fā)布,通知,廣播

            public void SendNewspaper(Newspaper newspaper) {

                newspaper.PublisherName = this.Name;

                if (Subscribers !=null) {

                    foreach (Action<object, PublisherArgs> handler in Subscribers.GetInvocationList()) {

                        try {

                            handler(this, new PublisherArgs(newspaper));

                        } catch(ApplicationException ex) {

                            Console.WriteLine(ex.Message);

                        }  }  }           

            } }

        static void Main(string[] args)

        {

            var publisher = new Publisher("出版社X");

            Person Aperson = new Person("A");

            Person Bperson = new Person("B");

            Company companyA = new Company("CompanyA");

            Company companyB = new Company("CompanyB");

            publisher.Subscribers += Aperson.SetNewspaper;//訂閱,注冊

            publisher.Subscribers -= Aperson.SetNewspaper;//退訂,取消注冊

            publisher.Subscribers += Bperson.SetNewspaper;//委托鏈

            publisher.Subscribers += (n,ex) => { throw new ApplicationException("have an erro"); };

            publisher.Subscribers += companyA.SetNewspaper;

            publisher.Subscribers += companyB.SetNewspaper;

            publisher.SendNewspaper(new Newspaper() { Title="標題",Content="內(nèi)容" });

            companyB.ReadNewspaper();

            } }   

}

泛型

C#中的泛型與JAVA中的泛型一模一樣。因此直接略過了

ArrayList

C#中arrylist與JAVA中的arrylist 用法基本一致,常規(guī)操作如下:

using System;

using System.Threading;

using UserNamespace;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using UserNamespace.Studnet;

using System.Collections;

namespace ConsoleApp1

{

    class Program

    {

        public static void ListOperation(ArrayList list) {

            //增,可以添加任意類型的元素

            list.Add(1);

            list.Add("hello world");

            list.Add(3.14);

            list.Add(true);

            list.AddRange(list);

            //批量添加,講一個集合添加到另外一個集合中

            list.AddRange(new int[] {1,2,3,4,5});

            list.Add(new int[] { 1, 2, 3, 4, 5 });

            Console.WriteLine(list.Count);

            //移除指定位置,第一個元素是 1

            list.Remove(1);

            //移除指定下標的元素從0開始

            list.RemoveAt(0);

            //從起點開始,移除多少個元素

            list.RemoveRange(0, 2);

            //指定下標修改元素

            list[2] = true;

            //2,批量修改元素

            list.SetRange(0,new string[] {"a","b","c","d" });

            //for-each 遍歷集合中的元素

            foreach (object obj in list) {

                Console.WriteLine(obj); }

            //通過枚舉器遍歷集合

            IEnumerator ienum = list.GetEnumerator();

            while (ienum.MoveNext()) {

                object obj = ienum.Current;

                Console.WriteLine(obj); }

            int index1 = list.IndexOf(3);//查詢某個元素第一次出現(xiàn)的下標

            int index2 = list.LastIndexOf(3);//查詢某個元素最后一次出現(xiàn)的下標

            int index3 = list.BinarySearch(3);//通過二分法查找某個元素的下標

            //集合排序,默認升序

            list.Sort();

            //集合翻轉(zhuǎn)

            list.Reverse();

            //集合中是否包含某個元素

            list.Contains(1);

            //集合拷貝

            object[] newList = new object[20];

            list.CopyTo(newList);

            //集合中插入元素

            list.Insert(0,"hello world");

            //集合中批量插入元素

            list.InsertRange(1,new bool[3]{ false,true,false}); }

        static void Main(string[] args)

        {

            ArrayList list = new ArrayList();

            ListOperation(list);

        } }}

arrylist自定義排序

當對對象進行排序的時候,需要實現(xiàn)一個接口 IComparable 或 IComparable<T> 來定義一個比較規(guī)則,然后再進行比較即可。

using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;

namespace ConsoleApp1
{

    class Person :IComparable{

        int age;

        public Person(int age)
        {
            this.age = age;
        }

        //IComparable 接口中的定義比較規(guī)則
        // =0 this==obj
        // >0 this > obj
        // <0 this < obj 
        public int CompareTo(object obj)
        {
            if (obj is Person) {

                Person anotherperson = obj as Person;
                return this.age - anotherperson.age;
            }


            return 0;

        }

        public override string ToString()
        {
            return this.age + " ";
        }
    }
    

    class Program
    {
        public static void ListOperation(ArrayList list) {
            //增,可以添加任意類型的元素
            list.Add(1);
            list.Add("hello world");
            list.Add(3.14);
            list.Add(true);


            list.AddRange(list);
            
            //批量添加,講一個集合添加到另外一個集合中
            list.AddRange(new int[] {1,2,3,4,5});
            list.Add(new int[] { 1, 2, 3, 4, 5 });

            Console.WriteLine(list.Count);
            //移除指定位置,第一個元素是 1
            list.Remove(1);
            //移除指定下標的元素從0開始
            list.RemoveAt(0);
            //從起點開始,移除多少個元素
            list.RemoveRange(0, 2);
            //指定下標修改元素
            list[2] = true;

            //2,批量修改元素
            list.SetRange(0,new string[] {"a","b","c","d" });

            //for-each 遍歷集合中的元素
            foreach (object obj in list) {
                
                Console.WriteLine(obj);
            }
            
            //通過枚舉器遍歷集合
            IEnumerator ienum = list.GetEnumerator();
            while (ienum.MoveNext()) {

                object obj = ienum.Current;
                Console.WriteLine(obj);
            }

            int index1 = list.IndexOf(3);//查詢某個元素第一次出現(xiàn)的下標
            int index2 = list.LastIndexOf(3);//查詢某個元素最后一次出現(xiàn)的下標
            int index3 = list.BinarySearch(3);//通過二分法查找某個元素的下標

            //集合排序,默認升序
            list.Sort();
            //集合翻轉(zhuǎn)
            list.Reverse();
            //集合中是否包含某個元素
            list.Contains(1);
            
            //集合拷貝
            object[] newList = new object[20];
            list.CopyTo(newList);

            //集合中插入元素
            list.Insert(0,"hello world");
            //集合中批量插入元素
            list.InsertRange(1,new bool[3]{ false,true,false});


        }

        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add(new Person(20));
            list.Add(new Person(2));
            list.Add(new Person(6));
            list.Add(new Person(7));
            list.Add(new Person(12));
            list.Add(new Person(28));
            list.Sort();
            IEnumerator ienum = list.GetEnumerator();
            while (ienum.MoveNext()){
                object obj = ienum.Current;
                Console.WriteLine(obj);
            }      }

List 集合

C# 的list集合與JAVA的list集合 基本相同,用法如下:

using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;

namespace ConsoleApp1
{

    class Person :IComparable{

        int age;

        public Person(int age)
        {
            this.age = age;
        }

        //IComparable 接口中的定義比較規(guī)則
        // =0 this==obj
        // >0 this > obj
        // <0 this < obj 
        public int CompareTo(object obj)
        {
            if (obj is Person) {

                Person anotherperson = obj as Person;
                return this.age - anotherperson.age;
            }
            return 0;
        }

        public override string ToString()
        {
            return this.age + " ";
        }
    }
    

    class Program
    {

        public static void ListOperation(List<string> list) {


            //增,可以添加任意類型的元素
          
            list.Add("hello world");
            list.Add("hello world 1");
            list.Add("hello world 2");

            list.AddRange(list);
            
            //批量添加,講一個集合添加到另外一個集合中
            list.AddRange(new string[] {"1 asd","2 aaa","3 hello"});
            

            Console.WriteLine(list.Count);
            //移除指定位置,第一個元素是 1
            list.Remove(1);
            //移除指定下標的元素從0開始
            list.RemoveAt(0);
            //從起點開始,移除多少個元素
            list.RemoveRange(0, 2);

            list.RemoveAll(name=>name== "hello world");
            
            //指定下標修改元素
            list[2] = "xiugai";

            //獲取一個集合中的子集
            List<string> sub = list.GetRange(1,2);

            //exists 判斷集合中是否存在滿足指定條件的元素
            //contains 判斷集合中是否包含指定元素
            bool result = list.Exists(name=>name=="hello");

            Console.WriteLine(result);
            //尋找集合中匹配的一項
            string oneString = list.Find( name => name == "hello");
            Console.WriteLine(oneString);

            //尋找集合中所有匹配項
            List<string> manyString = list.FindAll(name => name == "hello");
            
            //查詢符合條件的第一個元素的下標
            int indexF =list.FindIndex(name => name == "hello");
            //查詢符合條件的最后一個元素
            string lastElemet = list.FindLast(name => name == "hello");
            //查詢符合條件的最后一個元素的下標
            int lastElemetIndex = list.FindLastIndex(name => name == "hello");
            //移除符合條件的所有元素
            list.RemoveAll(name => name == "hello");

            //for-each 遍歷集合中的元素
            foreach (object obj in list) {
                
                Console.WriteLine(obj);
            }
            
            //通過枚舉器遍歷集合
            IEnumerator ienum = list.GetEnumerator();
            while (ienum.MoveNext()) {

                object obj = ienum.Current;
                Console.WriteLine(obj);
            }

            int index1 = list.IndexOf("3");//查詢某個元素第一次出現(xiàn)的下標
            int index2 = list.LastIndexOf("hello");//查詢某個元素最后一次出現(xiàn)的下標
           

            //集合排序,默認升序
            list.Sort();
            //集合翻轉(zhuǎn)
            list.Reverse();
            //集合中是否包含某個元素
            list.Contains(1);
            //集合拷貝
            object[] newList = new object[20];
        }
        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            ListOperation(list);
        }}}

棧和隊列
在C#里面封裝了stack數(shù)據(jù)結(jié)構(gòu),stack 的特點是先進后出,基本操作如下:

static void Main(string[] args)
        {
            //棧
            Stack stack = new Stack();

            stack.Push("first");
            stack.Push("second");
            stack.Push("third");
            
            //獲取棧頂元素
            Object ele = stack.Peek();
            Console.WriteLine(ele);

            //出棧
            Object popEle = stack.Pop();
            Console.WriteLine(popEle);

            //遍歷
            foreach (object obj in stack) {
                Console.WriteLine(obj);
            }

在C#里面封裝了Queue數(shù)據(jù)結(jié)構(gòu),Queue 的特點是先進先出,基本操作如下:

//隊列
            Queue queue = new Queue();
            queue.Enqueue("first");
            queue.Enqueue("second");
            queue.Enqueue("third");

            //獲取隊列首個元素
            Object obj1 = queue.Peek();
            Console.WriteLine(obj1);
            //將隊首元素移除隊列,返回值為剛剛移除的元素
            object obj2 = queue.Dequeue();
            Console.WriteLine(obj2);

            //遍歷
            foreach (object obj in queue)
            {
                Console.WriteLine(obj);
            }

HashTable
hashtable 是一種存取鍵值對的集合,在C#里面,hashtable是棧結(jié)構(gòu)并且,元素是DictionaryEntry,具體操作如下:

using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //實例化一個HashTable
            Hashtable table = new Hashtable();
            //增
            table.Add("key1","value");
            table.Add("key2", "value");
            table["key2"] = "修改了哦";
            table.Add("key3", "value");
            //獲取所有key
            ICollection keys = table.Keys;
            //先進后出
            foreach (DictionaryEntry tempDictionary in table) {
                Console.WriteLine(tempDictionary.Key+" "+ tempDictionary.Value);
            }
            table.Remove("key2");
            //通過所有key獲取value
            foreach (string tempstr in keys) {
                Console.WriteLine(tempstr);
            }  }  }}

Dictionary
Dictionary是一種鍵值對集合,但是和hashtable的不一樣的地方在于hastable在于元素的類型不需要一開始就強制聲明,而Dictionary必須聲明鍵與值的類型。具體操作如下:

using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;

namespace ConsoleApp1
{

   
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string,string> tempDictionary = new Dictionary<string, string>();
            //增加元素
            tempDictionary.Add("key1","hello");
            tempDictionary.Add("key2", "hello1");
            //按照鍵刪除元素
            tempDictionary.Remove("key1");
            //修改元素
            tempDictionary["key1"]= "修改了";

            foreach (Object obj in tempDictionary) {
                Console.WriteLine(obj);
            }

            foreach (KeyValuePair<string,string> obj in tempDictionary)
            {
                Console.WriteLine(obj.Key+" "+obj.Value);
            }

            //通過獲取所有key來遍歷
            ICollection keys = tempDictionary.Keys;

            foreach (string tempstr in keys)
            {
                Console.WriteLine(tempstr);
            }
        
    }
}

正則表達式
所有語言的正則表達式都是通用的,就不多介紹了,具體操作如下:

using System;
using System.Threading;
using UserNamespace;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UserNamespace.Studnet;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
     
        static void Main(string[] args)
        {
            //^:匹配一個字符串的開頭
            //$:匹配一個字符的結(jié)尾
            //實例化一個正則表達式的對象
            Regex regex = new Regex("^hello$");
            bool checkA = regex.IsMatch("hello");
            Console.WriteLine(checkA);

            regex = new Regex("hello");
            checkA = regex.IsMatch("hello world");
            Console.WriteLine(checkA);

            //[]:匹配一個字符,這一位字符可以是這個括號中的任何一個
            regex = new Regex("[qwhe]llo");
            checkA = regex.IsMatch("hello world");
            Console.WriteLine(checkA);

            regex = new Regex("^[qwhe]llo$");
            checkA = regex.IsMatch("hello world");
            Console.WriteLine(checkA);
            //[1-9]:匹配任何一個數(shù)字
            regex = new Regex("^[1-9]llo world$");
            checkA = regex.IsMatch("1ello world");
            Console.WriteLine(checkA);

            //[A-Za-z]:匹配任何一個字母
            regex = new Regex("^[A-Za-z]llo world$");
            checkA = regex.IsMatch("aello world");
            Console.WriteLine(checkA);
            
            //[A-Za-z0-9]:匹配任何一個字母和數(shù)字
            regex = new Regex("^[A-Za-z]llo world$");
            checkA = regex.IsMatch("1ello world");
            Console.WriteLine(checkA);

            //[^1-9] 表示這一位字符可以是[1,9] 之外的任何字符
            regex = new Regex("^1-9");
            checkA = regex.IsMatch("8");
            Console.WriteLine(checkA);


            //+:表示前面的一位字符表示了1次或多次

            regex = new Regex("^1+");
            checkA = regex.IsMatch("1111lo");
            Console.WriteLine(" + :"+checkA);


            //*:表示前面的一位字符表示了0次或多次
            regex = new Regex("^1*");
            checkA = regex.IsMatch("ok");
            Console.WriteLine(" * :" + checkA);

            //?:表示前面的一位字符表示了0次或1次
            regex = new Regex("^1?");
            checkA = regex.IsMatch("11111ok");
            Console.WriteLine(" ? :" + checkA);
            //{m}:前面的一位字符連續(xù)出現(xiàn)了m次

            regex = new Regex("^1{5}");
            checkA = regex.IsMatch("11111ok");
            Console.WriteLine("{m} :" + checkA);

            //{m,}:前面的一位字符至少連續(xù)出現(xiàn)了m次

            regex = new Regex("^1{1,}");
            checkA = regex.IsMatch("11111ok");
            Console.WriteLine("{m,} :" + checkA);

            //{m,n}:前面的一位字符連續(xù)出現(xiàn)了m到n次
            regex = new Regex("1{2,6}");
            checkA = regex.IsMatch("11111ok");
            Console.WriteLine("{m,n} :" + checkA);

            // \d :等價[0-9] 判斷前面的一位字符是否為數(shù)字 
            // \D:等價[^0-9] 判斷前面的一位字符是否為非數(shù)字

            //.: 通配符,可以匹配任意字符

            //判斷一個手機號是否為合法的
            bool checkphonenumber = Regex.IsMatch("13666669999","^1[35789]\\d{9}$");
            Console.WriteLine("checkphonenumber :" + checkphonenumber);
            //判斷一個郵箱號是否為合法的
            bool checkemail = Regex.IsMatch("13666669999@qq.com", "^.+@.+[\\.]com$");
            Console.WriteLine("checkemail :" + checkemail);

            //替換字符串為逗號  Regex.Replace可以實現(xiàn)批量替換
            string tempstr =Regex.Replace("lily  zhang,jhon,key"," {2,}",",");
            Console.WriteLine("tempstr :" + tempstr);

            //():表示分組
            //屏蔽手機號中間四位為*
            string phone = "13666669999";
            string parttern = "^(1[35789][0-9])(\\d{4})(\\d{4})$";
            //獲取每一個分組的字符串
            Match match = Regex.Match(phone, parttern);
            GroupCollection groups = match.Groups;//獲取所有分組
            string group1 = groups[1].Value;
            string group2 = groups[2].Value;
            string group3 = groups[3].Value;
            Console.WriteLine("phone:"+ group1+"****" + group3);
            Console.WriteLine("tempstr :" + tempstr);

            string qqNumber = "62346";
            //判斷QQ號的規(guī)則邏輯
            //正則表達式 以1到9開始的第一個數(shù)字,后面是4到10位的數(shù)字
            bool check =Regex.IsMatch(qqNumber,"^[1-9]\\d{4,10}$");
            Console.WriteLine(check);  } }}

總結(jié)
第二天結(jié)束了,依然有一點沒有完全學(xué)習(xí)完C#的基礎(chǔ)語法部分,但是也快了,估計明天就能學(xué)習(xí)完了,洗洗睡了先。估計明天就能開始學(xué)習(xí)unity了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容