/
aprogrammer
/
dotnet-docs
Обзор
Документация
Войти
/
aprogrammer
/
dotnet-docs
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
docs/csharp/fundamentals/tutorials/snippets/safelycast/patternmatching/Program.cs
58 строк
1 KB
Bill Wagner
Update tutorials to .NET 6 (#28404)
28 фев 2022, 21:50
Не верифицирован
28 фев 2022, 21:50
0e4df77
Код
Авторство
О чём код?
// <SnippetPatternMatchingIs> var g = new Giraffe(); var a = new Animal(); FeedMammals(g); FeedMammals(a); // Output: // Eating. // Animal is not a Mammal SuperNova sn = new SuperNova(); TestForMammals(g); TestForMammals(sn); static void FeedMammals(Animal a) { if (a is Mammal m) { m.Eat(); } else { // variable 'm' is not in scope here, and can't be used. Console.WriteLine($"{a.GetType().Name} is not a Mammal"); } } static void TestForMammals(object o) { // You also can use the as operator and test for null // before referencing the variable. var m = o as Mammal; if (m != null) { Console.WriteLine(m.ToString()); } else { Console.WriteLine($"{o.GetType().Name} is not a Mammal"); } } // Output: // I am an animal. // SuperNova is not a Mammal class Animal { public void Eat() { Console.WriteLine("Eating."); } public override string ToString() { return "I am an animal."; } } class Mammal : Animal { } class Giraffe : Mammal { } class SuperNova { } // </SnippetPatternMatchingIs>