Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

c# - When you implement two interfaces with the same method, how do you know which one is called?

If you have TheMethod() in interfaces I1 and I2, and the following class

class TheClass : I1, I2
{
    void TheMethod()
}

If something instantiates TheClass, how does it know which interface it is using?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If that's how the client code is using the class, it doesn't really matter. If it needs to do something interface specific, it should declare the interface it needs, and assign the class to that e.g.

I1 i = new TheClass()
i.TheMethod();

Of course, using your current implementation TheClass, it doesn't matter if declared i as I1, or I2, as you only have a single implementation.

If you want a separate implementation per interface, then you need to create explicit implementations ...

    void I1.TheMethod()
    {
        Console.WriteLine("I1");
    }

    void I2.TheMethod()
    {
        Console.WriteLine("I2");
    }

But keep in mind, explicit implementations cannot be public. You can implement just one explicitly, and leave the other as the default which can be public.

    void I1.TheMethod()
    {
        Console.WriteLine("I1");
    }

    public void TheMethod()
    {
        Console.WriteLine("Default");
    }

Have a look the msdn article for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...