1. 程式人生 > 其它 >c#基礎--學習筆記

c#基礎--學習筆記

c#基礎知識點,收集於網路。

C#基礎

c#集合--Collections

來源:TestAutomation.CSharp.Basics/CSharp.Collections/Collections/Collections_Dictionaries.cs

Arrays集合

建立:

            // defining array with size 5. 
            // But not assigns values
            int[] intArray1 = new int[5];

            // defining array with size 5 and assigning
            // values at the same time
            int[] intArray2 = new int[5] { 1, 2, 3, 4, 5 };

更新:

            string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };
            cars[0] = "Opel";
            Console.WriteLine(cars[0]);

輸出:

            // Accessing array values using for loop
            for (int i = 0; i < intArray3.Length; i++)
                Console.WriteLine(" " + intArray3[i]);

            // Accessing array values using foreach loop
            foreach (int i in intArray3)
                Console.WriteLine(" " + i);

排序:

            int[] myNumbers = { 5, 1, 8, 9 };
            Array.Sort(myNumbers);

Dictionary集合

建立c#集合:

方法一

IDictionary<int, string> numberNames = new Dictionary<int, string>();
            numberNames.Add(1, "One"); //adding a key/value using the Add() method
            numberNames.Add(2, "Two");
            numberNames.Add(3, "Three");

方法二

 //creating a dictionary using collection-initializer syntax
            var cities = new Dictionary<string, string>(){
                {"UK", "London, Manchester, Birmingham"},
                {"USA", "Chicago, New York, Washington"},
                {"India", "Mumbai, New Delhi, Pune"}
            };

遍歷Dictionary集合:

            foreach (KeyValuePair<int, string> kvp in numberNames)
                Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);

輸出集合內容:

Console.WriteLine(cities["UK"]); //prints value of UK key

查詢集合所含鍵:

 //use ContainsKey() to check for an unknown key
            if (cities.ContainsKey("France"))
            {
                Console.WriteLine(cities["France"]);
            }
 //use TryGetValue() to get a value of unknown key
            string result;

            if (cities.TryGetValue("France", out result))
            {
                Console.WriteLine(result);
            }

            //use ElementAt() to retrieve key-value pair using index
            for (int i = 0; i < cities.Count; i++)
            {
                Console.WriteLine("Key: {0}, Value: {1}",
                                                        cities.ElementAt(i).Key,
                                                        cities.ElementAt(i).Value);
            }

刪除集合內容:

            if (cities.ContainsKey("France"))
            { // check key before removing it
                cities.Remove("France");
            }

            cities.Clear(); //removes all elements

Hashtable集合

建立:

Hashtable numberNames = new Hashtable();
numberNames.Add(1, "One"); //adding a key/value using the Add() method

//creating a Hashtable using collection-initializer syntax
            var cities = new Hashtable(){
                {"UK", "London, Manchester, Birmingham"},
                {"USA", "Chicago, New York, Washington"},
                {"India", "Mumbai, New Delhi, Pune"}
            };

遍歷:

            foreach (DictionaryEntry de in numberNames)
                Console.WriteLine("Key: {0}, Value: {1}", de.Key, de.Value);

刪除

            if (cities.ContainsKey("France"))
            { // check key before removing it
                cities.Remove("France");
            }

            cities.Clear(); //removes all elements

List集合

建立:

            List<int> primeNumbers = new List<int>();
            primeNumbers.Add(1); // adding elements using add() method
            primeNumbers.Add(3);
            var cities = new List<string>();
            cities.Add("New York");
            cities.Add("London");
            //adding elements using collection-initializer syntax
            var bigCities = new List<string>()
                    {
                        "New York",
                        "London",
                        "Mumbai",
                        "Chicago"
                    };
var students = new List<Student>() {
                new Student(){ Id = 1, Name="Bill"},
                new Student(){ Id = 2, Name="Steve"},
                new Student(){ Id = 3, Name="Ram"},
                new Student(){ Id = 4, Name="Abdul"}
            };

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

查詢:

            var numbers = new List<int>() { 10, 20, 30, 40 };
            Assert.IsTrue(numbers.Contains(10)); // returns true

輸出:

            List<int> numbers = new List<int>() { 1, 2, 5, 7, 8, 10 };
            Console.WriteLine(numbers[0]); // prints 1

            // using foreach LINQ method
            numbers.ForEach(num => Console.WriteLine(num + ", "));//prints 1, 2, 5, 7, 8, 10,

            // using for loop
            for (int i = 0; i < numbers.Count; i++)
                Console.WriteLine(numbers[i]);
            //get all students whose name is Bill
            var result = from s in students
                         where s.Name == "Bill"
                         select s;

            foreach (var student in result)
                Console.WriteLine(student.Id + ", " + student.Name);

插入:

            var numbers = new List<int>() { 10, 20, 30, 40 };

            numbers.Insert(1, 11);// inserts 11 at 1st index: after 10.

刪除:

            var numbers = new List<int>() { 10, 20, 30, 40, 10 };
            numbers.Remove(10); // removes the first 10 from a list
            numbers.RemoveAt(2); //removes the 3rd element (index starts from 0)
            //numbers.RemoveAt(10); //throws ArgumentOutOfRangeException

SortedList:

類似於Dictionary

        public void Lists_SortedLists()
        {
            SortedList<string, string> cities = new SortedList<string, string>()
                                    {
                                        {"London", "UK"},
                                        {"New York", "USA"},
                                        { "Mumbai", "India"},
                                        {"Johannesburg", "South Africa"}
                                    };

            foreach (KeyValuePair<string, string> kvp in cities)
                Console.WriteLine("key: {0}, value: {1}", kvp.Key, kvp.Value);
        }

面向物件:

    public class MyClass
    {
        // Data member/ field
        public string myField = string.Empty;
        public string constructorField = string.Empty;

        // Constructor
        public MyClass()
        {
            constructorField = "Initialised when object is created";
        }

        // Method
        public string MyMethod(int parameter1, string parameter2)
        {
            string myString = ($"First Parameter {parameter1}, second parameter {parameter2}");
            Console.WriteLine(myString);

            return myString;
        }

        // Property
        public int MyAutoImplementedProperty { get; set; }

        private string myPropertyVar;

        // Custom Property
        public string MyProperty
        {
            get { return myPropertyVar; }
            set { myPropertyVar = value; }
        }
    }
}

繼承

  // Base class
    class base_Shape
    {
        protected int width;
        protected int height;
        protected int radius;
        public void setWidth(int w)
        {
            width = w;
        }
        public void setHeight(int h)
        {
            height = h;
        }

        public void setRadius(int r)
        {
            radius = r;
        }
    }

    // Derived class
    class derived_Rectangle : base_Shape
    {
        public int getArea()
        {
            return (width * height);
        }
    }

    // Derived class
    class derived_Circle : base_Shape
    {
        public double getArea()
        {
            return (3.14 * radius * radius);
        }
    }

抽象類:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Abstraction;

namespace CSharp.OOPs.OOPs
{
    [TestClass]
    public class OOPs_Abstraction
    {
        [TestMethod]
        public void OOPs_AbstractionImplementation()
        {
            Rectangle r = new Rectangle(10, 7);
            double a = r.area();
            Console.WriteLine("Area: {0}", a);
            Assert.AreEqual(70, r.area());
        }
    }
}

namespace Abstraction
{
    abstract class Shape
    {
        public abstract int area();
    }

    class Rectangle : Shape
    {
        private int length;
        private int width;

        public Rectangle(int a = 0, int b = 0)
        {
            length = a;
            width = b;
        }
        public override int area()
        {
            Console.WriteLine("Rectangle class area :");
            return (width * length);
        }
    }    
}

多型

網址:https://docs.microsoft.com/zh-cn/dotnet/csharp/fundamentals/object-oriented/polymorphism


1)執行時派生類被視為基類

2)通過派生類重寫基類的虛方法實現多型

public class Shape
{
    // A few example members
    public int X { get; private set; }
    public int Y { get; private set; }
    public int Height { get; set; }
    public int Width { get; set; }

    // Virtual method
    public virtual void Draw()
    {
        Console.WriteLine("Performing base class drawing tasks");
    }
}

public class Circle : Shape
{
    public override void Draw()
    {
        // Code to draw a circle...
        Console.WriteLine("Drawing a circle");
        base.Draw();
    }
}
public class Rectangle : Shape
{
    public override void Draw()
    {
        // Code to draw a rectangle...
        Console.WriteLine("Drawing a rectangle");
        base.Draw();
    }
}
public class Triangle : Shape
{
    public override void Draw()
    {
        // Code to draw a triangle...
        Console.WriteLine("Drawing a triangle");
        base.Draw();
    }
}

3)通過"foreach "遍歷派生類

var shapes = new List<Shape>
{
    new Rectangle(),
    new Triangle(),
    new Circle()
};

// Polymorphism at work #2: the virtual method Draw is
// invoked on each of the derived classes, not the base class.
foreach (var shape in shapes)
{
    shape.Draw();
}

4)虛方法的覆蓋:

a. 派生類可以覆蓋基類中的虛擬成員,定義新的行為。

b. 派生類繼承最近的基類方法而不覆蓋它,保留現有行為但允許進一步的派生類覆蓋該方法。

c. 派生類可以定義那些隱藏基類實現的成員的新的非虛擬實現

5)用新成員隱藏基類成員

new 關鍵字覆蓋虛方法

public class BaseClass
{
    public void DoWork() { WorkField++; }
    public int WorkField;
    public int WorkProperty
    {
        get { return 0; }
    }
}

public class DerivedClass : BaseClass
{
    public new void DoWork() { WorkField++; }
    public new int WorkField;
    public new int WorkProperty
    {
        get { return 0; }
    }
}

強制向上轉型,呼叫基類方法

DerivedClass B = new DerivedClass();
B.DoWork();  // Calls the new method.

BaseClass A = (BaseClass)B;
A.DoWork();  // Calls the old method.

6)防止派生類覆蓋虛擬成員

在類成員宣告中將sealed 關鍵字放在override 關鍵字之前。

public class C : B
{
    public sealed override void DoWork() { }
}

8)從派生類訪問基類虛擬成員

public class Base
{
    public virtual void DoWork() {/*...*/ }
}
public class Derived : Base
{
    public override void DoWork()
    {
        //Perform Derived's work here
        //...
        // Call DoWork on base class
        base.DoWork();
    }
}

使用:

 public void OOPs_Polymorhism_Dynamic()
        {
            Caller c = new Caller();
            Rectangle r = new Rectangle(10, 7);
            Triangle t = new Triangle(10, 5);

            c.CallArea(r);
            Assert.AreEqual(70, c.CallArea(r));

            c.CallArea(t);
            Assert.AreEqual(25, c.CallArea(t));
        }

介面

namespace TestAutomation.CSharp.OOPs
{
    interface IFile
    {
        void ReadFile();
        void WriteFile(string text);
    }
}
    public class FileInfo : IFile
    {
        public void ReadFile()
        {
            Console.WriteLine("Reading File");
        }

        public void WriteFile(string text)
        {
            Console.WriteLine("Writing to file");
        }

        public void InterfaceImplement()
        {
            IFile file1 = new FileInfo();
            FileInfo file2 = new FileInfo();

            file1.ReadFile();
            file1.WriteFile("content");

            file2.ReadFile();
            file2.WriteFile("content");
        }
    }

資料型別

顯示轉換

            int num1 = 10;
            int num2 = 4;
            double num3 = (double)num1 / num2;
            int num1 = 10;
            int num2 = 4;
            double num3 = Convert.ToDouble(num1) / Convert.ToDouble(num2);

            var checkFalse = Convert.ToBoolean(2 - 2);

            decimal decimalVal;
            string stringVal = "2,345.26";
            decimalVal = Convert.ToDecimal(stringVal);

            string dateString = "05/01/1996";
            ConvertToDateTime(dateString);

  //日期轉換         
		string dateString = "05/01/1996";
         ConvertToDateTime(dateString);

		private static void ConvertToDateTime(string value)
        	{
            DateTime convertedDate;
            try
            {
                convertedDate = Convert.ToDateTime(value);
                Console.WriteLine("'{0}' converts to {1} {2} time.",
                                  value, convertedDate,
                                  convertedDate.Kind.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("'{0}' is not in the proper format.", value);
            }
        }

隱式轉換

由 C# 以型別安全的方式執行。例如,從較小到較大的整數型別的轉換以及從派生類到基類的轉換

            int num1 = 10;
            double num2 = 15.8;
            var num3 = num1 + num2;//num3 == 25.8
            int num1 = 10;
            int num2 = 4;
            double num3 = num1 / num2;//num3 == 2
            int age = 30;
            Console.WriteLine($"My age is {age}");//My age is 30