【问题标题】:How can we use default implementation of different interfaces?我们如何使用不同接口的默认实现?
【发布时间】:2021-01-25 22:06:00
【问题描述】:

据我所知,我需要将继承类的实例向上转换到实现所需方法的接口,然后调用它。

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

如果我需要的具有不同方法的默认实现的接口很少怎么办?是否有一些模式可以解决这个问题,或者我应该总是使用 as 关键字来调用某个接口的方法?

【问题讨论】:

  • as 后跟 . 没有意义。如果您确定接口存在,请执行标准转换,如果您不确定,请使用.?

标签: c# .net oop interface default-interface-member


【解决方案1】:

除了@DavGarcia 的答案之外的另一个选项 - 引入一个结合所需接口并向上转换的接口:

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

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

【讨论】:

    【解决方案2】:

    如果你只调用一次该方法,我会像下面那样做。再丑,也是对的。

    ((IProcess)item).Do();
    

    如果您需要多次调用,还有一些其他选项可能更简洁。可以转换成界面:

    IProcess itemProcess = item;
    itemProcess.Do(); // Now call many times.
    

    通常,我认为您会将对象传递给需要接口的函数:

    void DoSomething(IProcess itemProcess) {
        itemProcess.Do();
    }
    
    DoSomething(item);
    

    【讨论】:

    【解决方案3】:

    您可以覆盖实现类中的方法并将控制权传递给默认实现。

    interface IProcess
    {
        void Do() { Console.WriteLine("doing"); }
    }
    
    interface IWait
    {
        void Wait() { Console.WriteLine("waiting"); }
    }
    
    class Example : IProcess, IWait 
    {
        public void Do() => ((IProcess)this).Do();
    
        public void Wait() => ((IWait)this).Wait();
    }
    

    现在你可以这样做了:

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

    【讨论】:

    • 实际上你不能——它会以 SO 结尾。 AFAIK ATM 无法在其实现中调用默认接口,只有一些 workarounds
    • 你确定吗?见this accepted answer
    • 是的,我是。在这个答案中,默认接口是在另一个方法中调用的,而不是在它自己的实现中。
    猜你喜欢
    • 2014-10-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 2019-03-19
    • 2021-01-19
    • 2015-07-31
    • 1970-01-01
    相关资源
    最近更新 更多