BasicKnowledgeCSharp/LessonsAndTasks/Lesson 79 - Интерфейсы - Явная реализация/Program.cs
Dvurechensky 058c8f2679 1.0
Main
2024-10-05 09:59:53 +03:00

74 lines
2.1 KiB
C#
Raw Permalink 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.

using System;
/*
* явная реализация интерфейсов
*/
/// <summary>
/// *класс может реализовать интерфейсы с одинаковыми методами
/// *если нам нужна разная реализация для этих методов, то интерфейсы нужно реализовать явно
/// </summary>
interface IFirstInterface
{
void Action();
}
interface ISecondInterface
{
void Action();
}
class Actions : IFirstInterface, ISecondInterface
{
public void Action()
=> Console.WriteLine($"{GetType().Name}: Action");
}
/// <summary>
/// Для таких случаев нужно использовать явную реализацию интерфейсов
/// </summary>
class OtherAction : IFirstInterface, ISecondInterface
{
/// <summary>
/// Модификаторы ставить нельзя из-за неоднозначности и отсутствия ссылки на интерфейс
/// </summary>
void IFirstInterface.Action()
{
Console.WriteLine($"IFirstInterface Action");
}
void ISecondInterface.Action()
{
Console.WriteLine($"ISecondInterface Action");
}
}
class Program
{
static void Main()
{
var act = new Actions();
Action_1(act);
Action_2(act);
var otherAction = new OtherAction();
Action_1(otherAction);
Action_2(otherAction);
((IFirstInterface)otherAction).Action();
((ISecondInterface)otherAction).Action();
// более безопасный с операторами as или is
if (otherAction is IFirstInterface firstInterface)
firstInterface.Action();
if (otherAction is ISecondInterface secondInterface)
secondInterface.Action();
Console.ReadKey();
}
public static void Action_1(IFirstInterface firstInterface)
=> firstInterface.Action();
public static void Action_2(ISecondInterface secondInterface)
=> secondInterface.Action();
}