BasicKnowledgeCSharp/LessonsAndTasks/Lesson 73 - Операторы as is, наследование и приведение типов/Program.cs
Dvurechensky bf6a7c2b4e 1.1
2025-05-12 02:48:54 +03:00

63 lines
1.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* Author: Nikolay Dvurechensky
* Site: https://www.dvurechensky.pro/
* Gmail: dvurechenskysoft@gmail.com
* Last Updated: 12 мая 2025 02:47:11
* Version: 1.0.3
*/
using System;
/*
* приведение типов и наследование
*
* использование операторов as и is
*/
class BasePoint
{
//
}
/// <summary>
/// *Все типы данных неявно унаследованы от типа Object
/// </summary>
class Point : BasePoint
{
public int X { get; set; }
public int Y { get; set; }
public void Print()
{
Console.WriteLine($"X:\t{X}");
Console.WriteLine($"Y:\t{Y}");
}
}
class Program
{
static void Main()
{
// ссылка базового класса может хранить любой тип наследников
object obj = new Point { X = 5, Y = 2 };
var point = (Point)obj; // приведение object к Point
point.Print();
Foo(obj);
Bar(obj);
Console.ReadKey();
}
static void Foo(object obj)
{
var point = obj as Point; // as - проверяет исключение при приведении типов
point?.Print();
}
static void Bar(object obj)
{
// is - позволяет сразу поместить данные в объект если прошел проверку
if (obj is Point point)
point.Print();
}
}