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
199 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 Reply

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();

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

...