Unable to call interface methods from another class

Below is my code:

public interface I1
{
    void method1();
}

public interface I2
{
    void method1();
}
class MyClass
{
    static void Main(string[] args)
    {
        One one = new One();

    }
}

public class One :I1,I2
{
    void I1.method1()
    {
        Console.WriteLine("This is method1 from Interface 1");
    }

    void I2.method1()
    {
        Console.WriteLine("This is method1 from Interface 2");
    }
}

I have below problems:

  • I cannot declare methods as Public in the One class, since these are interface methods.
  • I cannot call these interface implementations from an instance of MyClass in the main function.
+4
source share
4 answers

I cannot declare methods as Public in the One class, since these are interface methods.

This is only because you are using an explicit interface implementation . Assuming you really need two different implementations, you can make one of them implicit:

public void method1()
{
    Console.WriteLine("This is method1 from Interface 1");
}

void I2.method1()
{
    Console.WriteLine("This is method1 from Interface 2");
}

, public, one.method1() . , ( , ).

MyClass .

, , , one one.

:

One one = new One();
I1 i1 = one;
I2 i2 = one;
i1.method1();
i2.method1();

:

((I1)one).method1();
((I2)one).method1();
+6

. ,

One one = new One();
I1 x = (I1)one;
x.method1();
+2

, , One, , , :

public class One : I1, I2
{
    public void method1()
    {
        Console.WriteLine("Combined");
    }
}

3 :

var x = new One();
x.method1();
I1 i1 = x;
i1.method1();
I2 i2 = x;
i2.method1();
+1

. , , , , #, , , C, . #, , , .

, , .

2 , , , , #;)

, , :

One one = new One();
((I1)one).method1();
((I2)one).method1();

and we can have one publication that uses one interface:

public void method1()
{
    ((I1)this).method1();
}
+1
source

Source: https://habr.com/ru/post/1568311/


All Articles