How to call a specific explicitly declared interface method in C #

I have a doubt about how to call a specific interface method (Say IA or IB or In ...) in the following code. Please help me how to call. I commented out the lines of code where I declare the methods of the "public" interface, in which case it works. I don't know what to call it when I explicitly declare :( I am learning C # ....

interface IA
    {
        void Display();
    }
    interface IB
    {
        void Display();
    }
    class Model : IA, IB
    {
        void IA.Display()
        {
            Console.WriteLine("I am from A");
        }
        void IB.Display()
        {
            Console.WriteLine("I am from B");
        }
        //public void Display()
        //{
        //    Console.WriteLine("I am from the class method");
        //}

        static void Main()
        {
            Model m = new Model();
            //m.Display();
            Console.ReadLine();
        }
    }
+5
source share
4 answers

To call an explicit interface method, you need to use a variable of the appropriate type or directly apply to this interface:

    static void Main()
    {
        Model m = new Model();

        // Set to IA
        IA asIA = m;
        asIA.Display();

        // Or use cast inline
        ((IB)m).Display();

        Console.ReadLine();
    }
+9
source

The method that will be called depends on the type that calls it. For instance:

: . , , , .

static void Main(string[] args)
{
    // easy to understand version:
    IA a = new Model();
    IB b = new Model();

    a.Display();
    b.Display();

    // better practice version:
    Model model = new Model();

    (IA)model.Display();
    (IB)model.Display();
}

interface IA
{
    void Display();
}

interface IB
{
    void Display();
}

class Model : IA, IB
{
    void IA.Display()
    {
        Debug.WriteLine("I am from A");
    }

    void IB.Display()
    {
        Debug.WriteLine("I am from B");
    }            
}

:

I am from A
I am from B
+3

.

, . , . .

interface IA
{
   void Display();
}
interface IB
{
   void Display();
}

    public class Program:IA,IB
    {

        void IA.Display()
        {
            Console.WriteLine("I am from A");
        }

        void IB.Display()
        {
            Console.WriteLine("I am from B");
        }

        public static void Main(string[] args)
        {
           IA p1 = new Program();
           p1.Display();
           IB p2 = new Program();
           p2.Display();
        }
    }

:

I am from A
I am from B

DEMO.

+2

, :

IB ib = new Model();
ib.Display();

IA ia = (IA)ib;
ia.Display();
+2

All Articles