using System; publicclassDice { Random rnd = new Random(); publicDice() { } publicintRoll() { return rnd.Next(1, 7); } } classProgram { staticvoidMain(string[] args) { var d1 = new Dice(); ShowValue(d1); } privatestaticvoidShowValue(object o) { constint HIGH_ROLL = 6; if (o is Dice d && d.Roll() is HIGH_ROLL) Console.WriteLine($"The value is {HIGH_ROLL}!"); else Console.WriteLine($"The dice roll is not a {HIGH_ROLL}!"); } } // The example displays output like the following: // The value is 6!
using System; classProgram { staticvoidMain(string[] args) { object o = null; if (o isnull) { Console.WriteLine("o does not have a value"); } else { Console.WriteLine($"o is {o}"); } int? x = 10; if (x isnull) { Console.WriteLine("x does not have a value"); } else { Console.WriteLine($"x is {x.Value}"); } // 'null' check comparison Console.WriteLine($"'is' constant pattern 'null' check result : { o isnull }"); Console.WriteLine($"object.ReferenceEquals 'null' check result : { object.ReferenceEquals(o, null) }"); Console.WriteLine($"Equality operator (==) 'null' check result : { o == null }"); } // The example displays the following output: // o does not have a value // x is 10 // 'is' constant pattern 'null' check result : True // object.ReferenceEquals 'null' check result : True // Equality operator (==) 'null' check result : True }
using System; using System.Collections.Generic; using System.Linq; classProgram { staticvoidMain() { int[] testSet = { 100271, 234335, 342439, 999683 }; var primes = testSet.Where(n => Factor(n).ToList() isvar factors && factors.Count == 2 && factors.Contains(1) && factors.Contains(n)); foreach (int prime in primes) { Console.WriteLine($"Found prime: {prime}"); } } static IEnumerable<int> Factor(int number) { int max = (int)Math.Sqrt(number); for (int i = 1; i <= max; i++) { if (number % i == 0) { yieldreturn i; if (i != number / i) { yieldreturn number / i; } } } } } // The example displays the following output: // Found prime: 100271 // Found prime: 999683
二、C# 8.0中is的新语法
属性模式
匹配任何非"null"且属性设置为Length为2的对象,示例代码如下:
1 2 3
if (valueis { Length: 2 }) { }
实现验证的示例:
1 2 3 4 5 6
publicasync Task<IActionResult> Update(string id, ...) { if (ValidateId(id) is { } invalid) return invalid; ... }