【问题标题】:Can a C# class call an interface's default interface method from its own implementation?C# 类可以从自己的实现中调用接口的默认接口方法吗?
【发布时间】:2020-06-11 21:57:30
【问题描述】:

如果我有这样的默认接口方法:

public interface IGreeter
{
    void SayHello(string name) => System.Console.WriteLine($"Hello {name}!");
}

我可以让我的具体实现调用该默认方法吗?

public class HappyGreeter : IGreeter
{
    public void SayHello(string name)
    {
        // what can I put here to call the default method?
        System.Console.WriteLine("I hope you're doing great!!");
    }
}

所以调用:

var greeter = new HappyGreeter() as IGreeter;
greeter.SayHello("Pippy");

结果如下:

// Hello Pippy!
// I hope you're doing great!!

确实Calling C# interface default method from implementing class 表明我可以调用我的类未实现的方法,但正如预期的那样,在HappyGreeter.SaysHello 内添加对((IGreeter)this).SayHello(name); 的调用会导致堆栈溢出。

【问题讨论】:

  • 让我问你一个愚蠢的问题:如果你不能调用默认方法,它怎么会被调用?
  • 我认为这根本不是一个愚蠢的问题。这是我第一次使用默认界面成员。但是,我称之为的方式是将我的具体实例转换为具有默认成员的接口。它太酷了。我经常想看到 C# 中的特征,我认为一旦我习惯了它,这将是一个强大的补充。
  • 重复。他实际上并不愚蠢而且很棘手-但也在其他地方回答了。很有趣。
  • 可以取消关闭还是需要重新询问?非常感谢您抽出时间来管理社区。在这种情况下,我认为它可能被错误标记了。我很难找到这个问题的答案。
  • Can I have my concrete implementation call that default method? 我不这么认为,尽管似乎有计划通过base 来添加它。 docs.microsoft.com/en-us/dotnet/csharp/language-reference/…

标签: c# c#-8.0 default-interface-member


【解决方案1】:

据我所知,您不能在继承类中调用默认接口方法实现(尽管有proposals)。但是你可以从继承接口调用它:

public class HappyGreeter : IGreeter
{
    private interface IWorkAround : IGreeter
    {
        public void SayHello(string name)
        {
            (this as IGreeter).SayHello(name);
            System.Console.WriteLine("I hope you're doing great!!");
        }
    }

    private class WorkAround : IWorkAround {}

    public void SayHello(string name)
    {
        ((IWorkAround)new WorkAround()).SayHello(name);
    }
}

UPD

在我原来的答案中,我太想表明你可以在继承接口中调用base,但正如@Alexei Levenkov 在这种特殊情况下以更简洁的方式建议的那样:

public class HappyGreeter : IGreeter
{
    private class WorkAround : IGreeter { }
    private static readonly IGreeter _workAround = new WorkAround();

    public void SayHello(string name)
    {
        _workAround.SayHello(name);
        System.Console.WriteLine("I hope you're doing great!!");
    }
} 

【讨论】:

  • 那太恶心了。和天才。
  • @mjwills 同意第一部分)))
  • 如果我能用base(IGreeter).SayHello(name)就好了。
  • 不错。请注意,如果您只想调用默认实现class WorkAround: IGrreeter { } ... ((IWorkAround)new WorkAround()).SayHello(name);,则不需要额外的接口
【解决方案2】:

我知道这不是问题的答案,但下一个方法也可用于模拟 base 功能:

public interface IGreeter
{
    void SayHello(string name) => BaseSayHello(name);

    // This static method can be used in implementers of "IGreeter"
    // to emulate "base" functionality.
    protected static void BaseSayHello(string name) => System.Console.WriteLine($"Hello {name}!");
}

public class HappyGreeter : IGreeter
{
    public void SayHello(string name)
    {
        IGreeter.BaseSayHello(name);
        Console.WriteLine("I hope you're doing great!!");
    }
}

【讨论】:

    【解决方案3】:

    有一个非常简单的方法来处理这个问题:

    1. 将默认方法声明为静态。不用担心,您仍然可以在继承自它的类中覆盖它。
    2. 调用类的静态方法时,使用相同类型的语法调用默认方法,只用接口名代替类名。

    此代码适用于 C#8 或更高版本,如果针对 .NET Framework 构建,它将不起作用。我使用 C#9 在 Windows 10 上运行它,在 .NET 6 上运行,预览版 5。

    例子:

    public interface IGreeter
    {
       private static int DisplayCount = 0;
       public static void SayHello(string name)
       {
          DisplayCount++;
          Console.WriteLine($"Hello {name}! This method has been called {DisplayCount} times.");
       }
    }
    
    public class HappyGreeter : IGreeter
    {
       public void SayHello(string name)
       {
          // what can I put here to call the default method?
          IGreeter.SayHello(name);
          Console.WriteLine("I hope you're doing great!!");
       }
    }
    
    public class CS8NewFeatures
    {
       // This class holds the code for the new C# 8 features.
       //
       public void RunTests()
       {
          TestGreeting();
       }
    
       private void TestGreeting()
       {
          // Tests if a default method may be called after a class has implemented it.
          //
          var hg = new HappyGreeter();
          hg.SayHello("Pippy");
          hg.SayHello("Bob");
          hg.SayHello("Becky");
       }
    }
    

    示例输出:

    Hello Pippy! This method has been called 1 times.
    I hope you're doing great!!
    Hello Bob! This method has been called 2 times.
    I hope you're doing great!!
    Hello Becky! This method has been called 3 times.
    I hope you're doing great!!
    

    如本例所示,现在接口中也允许使用静态字段。

    如果由于某种原因您不能使用静态接口方法,那么您始终可以依赖以下技术:

    1. 将默认方法实现代码放入单独的静态方法中。
    2. 从默认实现方法调用此静态方法。
    3. 在接口方法的类实现的顶部调用此静态方法。

    例子:

    public class DefaultMethods
    {
       // This class is used to show that a static method may be called by a default interface method.
       //
       public static void SayHello(string name) => Console.WriteLine($"Hello {name}!");
    }
    
    public interface IGreeter
    {
       void SayHello(string name) => DefaultMethods.SayHello(name);
    }
    
    public class HappyGreeter : IGreeter
    {
       public void SayHello(string name)
       {
          // what can I put here to call the default method?
          DefaultMethods.SayHello(name);
          Console.WriteLine("I hope you're doing great!!");
       }
    }
    
    public class CS8NewFeatures
    {
       // This class holds the code for the new C# 8 features.
       //
       public void RunTests()
       {
          TestGreeting();
       }
    
       private void TestGreeting()
       {
          // Tests if a default method may be called after a class has implemented it.
          //
          var hg = new HappyGreeter();
          hg.SayHello("Bob");
       }
    }
    

    样本输出:

    Hello Bob!
    I hope you're doing great!!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-08
      • 2015-07-31
      • 2016-06-16
      • 2018-08-28
      • 2011-09-23
      • 2015-11-11
      • 2014-12-06
      • 1970-01-01
      相关资源
      最近更新 更多