Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - How can we use default implementation of different interfaces?

As I know, I need to upcast an instance of an inherited class to the interface where a needed method is implemented and then call it.

interface IProcess
{
    void Do() { Console.WriteLine("doing"); }
    //...
}

interface IWait
{
    void Wait() { Console.WriteLine("waiting"); }
    //...
}

class Example : IProcess, IWait { }


static void Main(string[] args)
{
    Example item = new Example();
    (item as IProcess).Do();
    (item as IWait).Wait();
}

What if there are few interfaces with default implementation of different methods that I need? Is there some pattern that can solve this or maybe I should always use as keyword to call a method of a certain interface?

question from:https://stackoverflow.com/questions/65893072/how-can-we-use-default-implementation-of-different-interfaces

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

1 Answer

0 votes
by (71.8m points)

Another option in addition to @DavGarcia's answer - introduce an interface combining the needed ones and upcast to it:

interface IExample : IProcess, IWait { }    
class Example : IExample { }

IExample item = new Example();
item.Do();
item.Wait();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...