来源:TestAutomation.CSharp.Basics/CSharp.Collections/Collections/Collections_Dictionaries.cs
创建:
// 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);
创建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 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<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