// Declare the generic class. public class GenericList { public void Add(T input) { } } class TestGenericList { private class ExampleClass { } static void Main() { // Declare a list of type int. GenericList list1 = new GenericList(); list1.Add(1);
// Declare a list of type string. GenericList list2 = new GenericList(); list2.Add("");
// Declare a list of type ExampleClass. GenericList list3 = new GenericList(); list3.Add(new ExampleClass()); } }
// Assignment compatibility. string str = "test"; // An object of a more derived type is assigned to an object of a less derived type. object obj = str; // Covariance. IEnumerable strings = new List(); // An object that is instantiated with a more derived type argument // is assigned to an object instantiated with a less derived type argument. // Assignment compatibility is preserved. IEnumerable
// This class is mutable. Its data can be modified from // outside the class. class Customer { // Auto-implemented properties for trivial get and set public double TotalPurchases { get; set; } public string Name { get; set; } public int CustomerID { get; set; }
// Constructor public Customer(double purchases, string name, int ID) { TotalPurchases = purchases; Name = name; CustomerID = ID; }
// Methods public string GetContactInfo() { return "ContactInfo"; } public string GetTransactionHistory() { return "History"; }
// .. Additional methods, events, etc. }
class Program { static void Main() { // Intialize a new object. Customer cust1 = new Customer(4987.63, "Northwind", 90108);
// Modify a property. cust1.TotalPurchases += 499.99; } }
匿名类型
Code
1 2 3 4 5 6
var v = new { Amount = 108, Message = "Hello" }; // Rest the mouse pointer over v.Amount and v.Message in the following // statement to verify that their inferred types are int and n . Console.WriteLine(v.Amount + v.Message);
Func square = x => x * x; Console.WriteLine(square(5)); // Output: // 25
表达式树
扩展方法
扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。
var
Code
1 2 3
var i = 10; // Implicitly typed. int i = 10; // Explicitly typed.
分部方法
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
namespace PM { partial class A { partial void OnSomethingHappened(string s); }
// This part can be in a separate file. partial class A { // Comment out this method and the program // will still compile. partial void OnSomethingHappened(String s) { Console.WriteLine("Something happened: {0}", s); } } }
对象和集合初始值设定项
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class Cat { // Auto-implemented properties. public int Age { get; set; } public string Name { get; set; }
public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)
泛型中的协变和逆变
Code
1 2 3 4 5 6 7
IEnumerable d = new List(); IEnumerable b = d;
Action b = (target) => { Console.WriteLine(target.GetType().Name); }; Action d = b; d(new Derived());
类型等效性和嵌入的互操作类型
C# 5.0版 - 2012
异步编程
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
private DamageResult CalculateDamageDone() { // Code omitted: // // Does an expensive calculation and returns // the result of that calculation. }
calculateButton.Clicked += async (o, e) => { // This line will yield control to the UI while CalculateDamageDone() // performs its work. The UI thread is free to perform other work. var damageResult = await Task.Run(() => CalculateDamageDone()); DisplayDamage(damageResult); };
public static IEnumerable AlphabetSubset3(char start, char end) { if (start < 'a' || start > 'z') throw new ArgumentOutOfRangeException(paramName: nameof(start), message: "start must be a letter"); if (end < 'a' || end > 'z') throw new ArgumentOutOfRangeException(paramName: nameof(end), message: "end must be a letter");
if (end <= start) throw new ArgumentException($"{nameof(end)} must be greater than {nameof(start)}");
return alphabetSubsetImplementation();
IEnumerable alphabetSubsetImplementation() { for (var c = start; c < end; c++) yield return c; } }
更多的expression-bodied成员
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Expression-bodied constructor public ExpressionMembersExample(string label) => this.Label = label;
public static ref int Find(int[,] matrix, Func predicate) { for (int i = 0; i < matrix.GetLength(0); i++) for (int j = 0; j < matrix.GetLength(1); j++) if (predicate(matrix[i, j])) return ref matrix[i, j]; throw new InvalidOperationException("Not found"); }
ref var item = ref MatrixSearch.Find(matrix, (val) => val == 42); Console.WriteLine(item); item = 24; Console.WriteLine(matrix[4, 2]);
弃元
二进制文本和数字分隔符
引发表达式
C# 8.0版 - 2019
Readonly 成员
Code
1 2 3
public readonly override string ToString() => $"({X}, {Y}) is {Distance} from the origin";
默认接口方法
在更多位置中使用更多模式
* switch表达式
Code
1 2 3 4 5 6 7 8 9 10 11 12 13
public static RGBColor FromRainbow(Rainbow colorBand) => colorBand switch { Rainbow.Red => new RGBColor(0xFF, 0x00, 0x00), Rainbow.Orange => new RGBColor(0xFF, 0x7F, 0x00), Rainbow.Yellow => new RGBColor(0xFF, 0xFF, 0x00), Rainbow.Green => new RGBColor(0x00, 0xFF, 0x00), Rainbow.Blue => new RGBColor(0x00, 0x00, 0xFF), Rainbow.Indigo => new RGBColor(0x4B, 0x00, 0x82), Rainbow.Violet => new RGBColor(0x94, 0x00, 0xD3), _ => throw new ArgumentException(message: "invalid enum value", paramName: nameof(colorBand)), };
public static string RockPaperScissors(string first, string second) => (first, second) switch { ("rock", "paper") => "rock is covered by paper. Paper wins.", ("rock", "scissors") => "rock breaks scissors. Rock wins.", ("paper", "rock") => "paper covers rock. Paper wins.", ("paper", "scissors") => "paper is cut by scissors. Scissors wins.", ("scissors", "rock") => "scissors is broken by rock. Rock wins.", ("scissors", "paper") => "scissors cuts paper. Scissors wins.", (_, _) => "tie" };
* 位置模式
Code
1 2 3 4 5 6 7 8 9 10 11
static Quadrant GetQuadrant(Point point) => point switch { (0, 0) => Quadrant.Origin, var (x, y) when x > 0 && y > 0 => Quadrant.One, var (x, y) when x < 0 && y > 0 => Quadrant.Two, var (x, y) when x < 0 && y < 0 => Quadrant.Three, var (x, y) when x > 0 && y < 0 => Quadrant.Four, var (_, _) => Quadrant.OnBorder, _ => Quadrant.Unknown };
static int WriteLinesToFile(IEnumerable lines) { using var file = new System.IO.StreamWriter("WriteLines2.txt"); // Notice how we declare skippedLines after the using statement. int skippedLines = 0; foreach (string line in lines) { if (!line.Contains("Second")) { file.WriteLine(line); } else { skippedLines++; } } // Notice how skippedLines is in scope here. return skippedLines; // file is disposed here }
静态本地函数
Code
1 2 3 4 5 6 7 8 9
int M() { int y = 5; int x = 7; return Add(x, y);
static int Add(int left, int right) => left + right; }
异步流
Code
1 2 3 4 5 6 7 8 9
public static async System.Collections.Generic.IAsyncEnumerable GenerateSequence() { for (int i = 0; i < 20; i++) { await Task.Delay(100); yield return i; } }
var words = new string[] { // index from start index from end "The", // 0 ^9 "quick", // 1 ^8 "brown", // 2 ^7 "fox", // 3 ^6 "jumped", // 4 ^5 "over", // 5 ^4 "the", // 6 ^3 "lazy", // 7 ^2 "dog" // 8 ^1 }; // 9 (or words.Length) ^0
var quickBrownFox = words[1..4]; var lazyDog = words[^2..^0]; var allWords = words[..]; // contains "The" through "dog". var firstPhrase = words[..4]; // contains "The" through "fox" var lastPhrase = words[6..]; // contains "the", "lazy" and "dog"
Null合并赋值
Code
1 2 3 4 5 6 7 8 9 10
List numbers = null; int? i = null;
numbers ??= new List(); numbers.Add(i ??= 17); numbers.Add(i ??= 20);