简体   繁体   English

使用c#中的扩展方法实现接口

[英]Implementing Interface using extension methods in c#

I have an Interface: 我有一个界面:

public interface IMessager
{
    void ShowMessage();
}

Is there any way to implement this interface using extension methods? 有没有办法使用扩展方法实现此接口?

public static class Extensions
{
  public static void ShowMessage(this MyClass e)
  {
      Console.WriteLine("Extension");
  }
}

and a class that implement it: 以及实现它的类:

public class MyClass:IMessager
{
    public void ShowMessage()
    {
        ShowMessage(); // I expect that program write "Extension" in console
    }
}

But when I run the program I get the System.StackOverflowException . 但是当我运行程序时,我得到了System.StackOverflowException

The code you posted is just a method calling itself recursively (hence the StackOverflowException ). 您发布的代码只是一个递归调用自身的方法(因此是StackOverflowException )。

I'm not entirely sure what you're trying to accomplish but to answer your question 我不完全确定你要完成什么,但要回答你的问题

Is there any way to implement this interface using extension methods? 有没有办法使用扩展方法实现此接口?

No. 没有。

To be a bit more pragmatic about this though, if your aim is to only write your method once you have a few options: 但是,为了更加务实,如果你的目标只是在你有几个选择后编写你的方法:

1. Call the extension explicitly 1.明确调用扩展名

public class MyClass:IMessager
{
    public void ShowMessage()
    {
        Extensions.ShowMessage(this);
    }
}

although as pointed out in comments, this basically defeats the point of using the extension method. 虽然正如评论中所指出的那样,这基本上违背了使用扩展方法的要点。 Additionally there is still "boiler-plate code" such that every time you implement your interface you have to call the static method from within the method (not very DRY ) 此外,还有“样板代码”,这样每次实现界面时都必须从方法中调用静态方法(不是非常

2. Use an abstract class instead of an interface 2.使用抽象类而不是接口

public abstract class MessengerBase
{
    public void ShowMethod() { /* implement */ }
}

public class MyClass : MessengerBase {}

...

new MyClass().ShowMethod();

This issue with this though is that you can't inherit from multiple classes. 这个问题是你不能从多个类继承。

3. Use extension on the interface 3.在界面上使用扩展名

public interface IMessenger { /* nothing special here */ }

public class MyClass : IMessenger { /* also nothing special */ }

public static class MessengerExtensions
{
    public static void ShowMessage(this IMessenger messenger)
    {
        // implement
    }
}

...

new MyClass().ShowMessage();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM