C#8支持接口中的默认方法实现。我的想法是向这样的类中注入日志记录方法:
C# 8 supports default method implementations in interfaces. My idea was to inject a logging method into classes like this:
public interface ILoggable { void Log(string message) => DoSomethingWith(message); } public class MyClass : ILoggable { void MyMethod() { Log("Using injected logging"); // COMPILER ERROR } }我收到一个编译器错误:该名称在当前上下文中不存在。
I get a compiler error: "The name does not exist in the current context"
是否不可能以这种方式使用默认方法实现?
Is it impossible to use default method implementations in this way?
编辑:
有关C#规则的正确答案,请参见接受的答案。有关更简洁的解决方案(我的问题的初衷!),请参阅下面的自己的答案。
For the correct response regarding C# rules, see the accepted answer. For a more concise solution (the original idea of my question!) see my own answer below.
推荐答案请参阅 docs.microsoft/zh-cn/dotnet/csharp/tutorials/default-interface-members-versions
必须将 SampleCustomer 转换为 ICustomer 。 SampleCustomer 类不需要为 ComputeLoyaltyDiscount 提供实现;由 ICustomer 界面提供。但是, SampleCustomer 类不会从其接口继承成员。该规则没有改变。为了调用在接口中声明和实现的任何方法,该变量必须是接口的类型,在此示例中为 ICustomer 。
That cast from SampleCustomer to ICustomer is necessary. The SampleCustomer class doesn't need to provide an implementation for ComputeLoyaltyDiscount; that's provided by the ICustomer interface. However, the SampleCustomer class doesn't inherit members from its interfaces. That rule hasn't changed. In order to call any method declared and implemented in the interface, the variable must be the type of the interface, ICustomer in this example.
所以方法类似于
public class MyClass : ILoggable { void MyMethod() { ILoggable loggable = this; loggable.Log("Using injected logging"); } }更多推荐
从实现类调用C#接口默认方法
发布评论