C# How To系列

C# How To系列

1.實例化一個類

using System;
namespace Csharp_how_to
{
    class Program
    {
        static void Main(string[] args)
        {
            // method 1
            Student stu1 = new Student();
            stu1.Name = "tom";
            stu1.Id = 100;

            // method 2
            Student stu2 = new Student
            {
                Name = "jhon",
                Id = 99,
            };

            // method 3
            Student stu3 = new Student("james", 101);

            Console.WriteLine(stu1.ToString());
            Console.WriteLine(stu2.ToString());
            Console.WriteLine(stu3.ToString());

            Console.ReadKey();
        }
    }

    class Student
    {
        public string Name { get; set; }
        public int Id { get; set; }

        // no param constructor
        public Student()
        {

        }
        // two param constrcutor
        public Student(string name, int id)
        {
            this.Name = name;
            this.Id = id;
        }


        public override string ToString()
        {
            return "Name:" + this.Name + "\t" + "Id:" + this.Id;
        }

    }
}
//Running Result:

//Name:tom        Id:100
//Name:jhon       Id:99
//Name:james      Id:101

2.索引器

using System;
using System.Collections.Generic;
namespace Csharp_how_to
{
    class Program
    {
        static void Main(string[] args)
        {

            var team = new BaseballTeam
            {
                ["RF"] = "Jhon",
                [4] = "Danie",
                ["CF"] = "Mike",
            };

            Console.WriteLine(team[4]);

            Console.ReadKey();
        }
    }
    public class BaseballTeam
    {
        private string[] players = new string[9];
        private readonly List<string> positionAbbreviations = new List<string>()
        {
            "p","C","1B","2B","3B","SS","LF","CF","RF"
        };
        // indexer
        public string this[int position]
        {
            // Baseball positions are 1-9
            get { return players[position - 1]; }
            set { players[position - 1] = value; }
        }
        // indexer

        public string this[string position]
        {
            get { return players[positionAbbreviations.IndexOf(position)]; }
            set { players[positionAbbreviations.IndexOf(position)] = value; }
        }

    }
}

3.通過Collection初始化器初始化字典

using System;
using System.Collections.Generic;
using System.Linq;

namespace Csharp_how_to
{
    class Program
    {
        static void Main()
        {
            var students = new Dictionary<int, StudentName>()
            {
                {111,new StudentName{FirstName="Sachin",LastName="Karnik",Id=211} },
                {112,new StudentName{FirstName="Dina",LastName="Abbas",Id=222} },
                {113,new StudentName{FirstName="Jhon",LastName="Mikle",Id=233} }
            };
            foreach(var index in Enumerable.Range(111,3))
            {
                Console.WriteLine($"Student{index} is {students[index].FirstName}·{students[index].LastName}");
            }

            Console.ReadKey();
        }
    }
    class StudentName
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Id { get; set; }
    }
    
}

4.Partial Class/Method

對於一些比較大的項目,可以把同一個類分給好幾個程序員去編碼,最後編譯的時候編譯器會把標名爲partial字樣的類會合在一起編譯嗎,與寫進一個class 沒有區別。下面以StudentName類爲例說名

// 這個部分定義兩個屬性,姓和名
partial class StudentName
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    // 這個部分再定義一個屬性Id和構造器
    partial class StudentName
    {
        public int Id { get; set; }
        public StudentName(string f,string l,int id)
        {
            this.FirstName = f;
            this.LastName = l;
            this.Id = id;
        }
        public override ToString()
        {
            return "Name:"+this.FirstName+"·"+this.LastName+"\t"+"Id:"+this.Id;
        }
    }
    public static void Main(string[] args)
    {
        Student student=new Student("mikle","Jhon",111);
        Console.WriteLine(student.ToString())
    }

同理,接口也可以分成好幾個部分編碼,效果同上。以IAnimal接口爲例說明

using System;
using System.Collections.Generic;
using System.Linq;

namespace Csharp_how_to
{
    public partial interface IAnimal
    {
         void Eat();
        void Run();
    }
    public partial interface IAnimal
    {
        void Sleep();
        void Shout();
    }

    public class Animal : IAnimal
    {
        public void Eat()
        {
            Console.WriteLine("I am eating");
        }

        public void Run()
        {
            Console.WriteLine("I am running");
        }

        public void Shout()
        {
            Console.WriteLine("I am shouting");
           
        }

        public void Sleep()
        {
            Console.WriteLine("I am slepping");
        }
    }

    class Program
    {
        static void Main()
        {
            Animal animal = new Animal();
            animal.Eat();
            animal.Run();
            animal.Shout();
            animal.Sleep();
            animal.Sleep();
            Console.ReadKey();
        }
    }
}

同理,方法也可以寫成Partial

using System;
using System.Collections.Generic;
using System.Linq;
namespace Csharp_how_to
{
    public partial class Animal
    {
      partial void Sleep();
    }
    public partial class Animal
    {
        partial void Sleep()
        {
            Console.WriteLine("ZZZ~~~");
        }
    }
}

5.方法傳類參數和結構體參數的區別

因爲結構體是值類型的,把一個值類型的數值作爲方法的參數傳入時會複製一份新的給方法,不會拿到最原始的數據地址,所以結構體作爲方法參數時不能對其進行修改。
類是引用類型的,一個類作爲方法的參數傳入時同樣會複製一份出來給方法用,同時這個新複製出來的數值也是指向原先數值的地址,即可以根據這個地址去拿到最先的那個變量,所以可以通過傳入的參數來對原來的數字進行修改。下面以實例說明:

using System;
namespace ConsoleApp1
{
    public class TheClass
    {
        public string willIChange;
    }
    public struct TheStrcut
    {
        public string willIChange;
    }
    
    class Program
    {
        static void classTaker(TheClass c)
        {
            c.willIChange = "Changed";
        }
        static void strcutTaker(TheStrcut s)
        {
            s.willIChange = "Changed";
        }

        static void Main(string[] args)
        {
            TheClass testClass = new TheClass();
            TheStrcut testStruct = new TheStrcut();

            testClass.willIChange = "Not Changed";
            testStruct.willIChange = "Not Changed";

            classTaker(testClass);
            strcutTaker(testStruct);

            Console.WriteLine($"Class filed={testClass.willIChange}");
            Console.WriteLine($"Struct filed={testStruct.willIChange}");

            Console.ReadKey();
        }
    }
}

6.運算符重載

using System;
namespace ConsoleApp1
{
    public readonly struct Fraction
    {
        public readonly int num;
        public readonly int den;
        public Fraction(int numerator,int denominator)
        {
            if(denominator==0)
            {
                throw new ArgumentException("Denomintor can not be zero.", nameof(denominator));
            }
            this.num = numerator;
            this.den = denominator;
        }

        // operator overload
        public static Fraction operator +(Fraction a) => a;
        public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den);
        public static Fraction operator +(Fraction a, Fraction b) => new Fraction(a.den * b.num + a.num * b.den, a.den * b.den);
        public static Fraction operator -(Fraction a, Fraction b) => a + (-b);
        public static Fraction operator *(Fraction a, Fraction b) => new Fraction(a.num * b.num, a.den * b.den);
        public override string ToString()
        {
            return $"{this.num}/{this.den}";
        }
    }
    class Program
    {

        static void Main(string[] args)
        {
            Fraction fraction1 = new Fraction(1, 2);
            Fraction fraction2 = new Fraction(3, 2);
            Console.WriteLine($"{fraction1.ToString()} + {fraction2.ToString()} = {(fraction1+fraction2).ToString()}");
            Console.WriteLine($"-{fraction1.ToString()} = {(-fraction1).ToString()}");
            Console.WriteLine($"{fraction1.ToString()} - {fraction2.ToString()} = {(fraction1-fraction2).ToString()}");
            Console.WriteLine($"{fraction1.ToString()} * {fraction2.ToString()} = {(fraction1*fraction2).ToString()}");

            Console.ReadKey();
        }
    }
}

7.修改一個字符串

字符串在.Net中是不可修改的,對字符串進行的增刪的結果都是新生成一個字符串再返回的,下面以實例說明。

using System;
namespace StringModifier
{
    class Program
    {
        var source="The mountains are behind the clouds today.";
        static void Main(string[] args)
        {
            var replaced=source.Replace("behind","front");
            Console.WriteLine($"source:{source}");
            Console.WriteLine($"replaced:{replaced}");
            Console.ReadKey();
        }
    }
}

8.判斷一個字符串是不是數值類型的

可以用tryparse方法來進行判斷,下面是實例說明:

using System;
namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {

            int i = 0;
            bool res = int.TryParse("2", out i);
            if(res)
            {
                Console.WriteLine($"{i+1}");
            }
            i = 0;
            bool res1 = int.TryParse("we2", out i);
            if (res)
            {
                Console.WriteLine($"{i}");
            }
            Console.ReadKey();
        }
    }
}

9.用LINQ查詢ArrayList

using System;
using System.Collections;
using System.Linq;
namespace ConsoleApp1
{
    class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
       public int[] Scores { get; set; }
        public override string ToString()
        {
            string res = string.Empty;
            res += "FirstName:" + this.FirstName+"\t";
            res += "LastName:" + this.LastName+"\t";
            for(int i=0;i<this.Scores.Length;i++)
            {
                res += $"第{i+1}個科目成績爲:{this.Scores[i]}"+"\t";
            }
            return res;
        }
    }
    class Program
    {

        static void Main(string[] args)
        {

            ArrayList list = new ArrayList();
            list.Add(new Student { FirstName = "張", LastName = "三", Scores = new int[] { 100, 90 } });
            list.Add(new Student { FirstName = "李", LastName = "四", Scores = new int[] { 98, 90 } });
            list.Add(new Student { FirstName = "張", LastName = "六", Scores = new int[] { 96, 90 } });
            list.Add(new Student { FirstName = "張", LastName = "八", Scores = new int[] { 90, 80 } });

            var query = from Student stu in list
                        where stu.Scores[0] > 95 && stu.FirstName == "張"
                        select stu;
            foreach(var item in query)
            {
                Console.WriteLine(item);
            }


            Console.ReadKey();
        }
    }
}

10.LINQ查詢中使用lambda表達式

using System;
using System.Collections;
using System.Linq;
namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {

            // Data source
            int[] scores = new int[] { 100, 50, 60, 70, 40, 98, 78, 69 };

            // The call to count forces iteration of the source
            int highScoreCount = scores.Where(x => x > 90).Count();
            Console.WriteLine(highScoreCount);
            Console.ReadKey();
        }
    }
}


11.LINQ中的運算符All,Any,Contains的用法

All和Any運算符都返回一個布爾類型的結果,All是當所有的數值都滿足條件時纔會返回True,Any是隻要存在滿足條件的數值就返回True。Contains是模糊匹配

using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
    class Market
    {
        public string Name { get; set; }
        public string[] Items { get; set; }
    }
    class Program
    {

        static void Main(string[] args)
        {
            List<Market> markets = new List<Market>
    {
        new Market { Name = "Emily's", Items = new string[] { "kiwi", "cheery", "banana" } },
        new Market { Name = "Kim's", Items = new string[] { "melon", "mango", "olive" } },
        new Market { Name = "Adam's", Items = new string[] { "kiwi", "apple", "orange" } },
        new Market { Name = "Adam1's", Items = new string[] { "kiwi","yakiwi","apple", "orange" } },
    };

            // Determine which market have all fruit names length equal to 5
            IEnumerable<string> names = from market in markets
                                        where market.Items.All(item => item.Length == 5)
                                        select market.Name;
            // Determine which market have all fruit names length equal to 5
            IEnumerable<string> names2 = from market in markets
                                        where market.Items.Any(item => item.Length == 4)
                                        select market.Name;


            IEnumerable<string> containsNames = from market in markets
                                                where market.Items.Contains("kiwi")
                                                select market.Name;
            Console.WriteLine("All");
            foreach (string name in names)
            {
                Console.WriteLine($"{name} market");
            }
            Console.WriteLine("Any");
            foreach (string name in names2)
            {
                Console.WriteLine($"{name} market");
            }

            Console.WriteLine("Contains");
            foreach(var item in containsNames)
            {
                Console.WriteLine(item);
            }
        }
    }

}


12.LINQ中使用排序

  • 按照一個值來排序
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
    class Student
    {
        public string Name { get; set; }
        public int Score { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
            List<Student> students = new List<Student>();
            for(int i=0;i<30;i++)
            {
                Student stu = new Student
                {
                    Name = "Name" + i.ToString(),
                    Score = new Random().Next(100)
                };
                students.Add(stu);
            }

            var query = from Student stu in students
                        where stu.Score > 60//過濾成績幾個的同學
                        orderby stu.Score//按成績排序
                        select stu;
            foreach (var item in query)
            {
                Console.WriteLine("Name:"+item.Name+"\t"+"Score:"+item.Score);
            }

            Console.ReadKey();
        }
    }

}
// 運行結果
Name:Name1      Score:74
Name:Name14     Score:76
Name:Name16     Score:76
Name:Name23     Score:76
Name:Name2      Score:77
Name:Name13     Score:86
Name:Name21     Score:88
Name:Name22     Score:91
Name:Name3      Score:92
Name:Name20     Score:93
  • 按照裏兩個值來排序,如果數學成績相等,再比較文化課成績
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
    class Student
    {
        public string Name { get; set; }
        public int MathScore { get; set; }
        public int CultureScore { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
            List<Student> students = new List<Student>();
            for(int i=0;i<30;i++)
            {
                Student stu = new Student
                {
                    Name = "Name" + i.ToString(),
                    MathScore = new Random().Next(90,100),
                    CultureScore = new Random().Next(100),
                };
                students.Add(stu);
            }

            var query = from Student stu in students
                        where stu.MathScore > 60 && stu.CultureScore>60
                        orderby stu.MathScore,stu.CultureScore
                        select stu;
            foreach (var item in query)
            {
                Console.WriteLine("Name:"+item.Name+"\t"+"MathScore:"+item.MathScore+"\t"+"CultureScore:"+item.CultureScore);
            }

            Console.ReadKey();
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章