从实现类调用C#接口默认方法 [英] Calling C# interface default method from implementing class
问题描述
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.
推荐答案
请参阅 https://docs.microsoft.com/zh-cn/dotnet/csharp/tutorials/default-interface-members-versions
必须将
SampleCustomer
转换为ICustomer
。SampleCustomer
类不需要为ComputeLoyaltyDiscount
提供实现;由ICustomer
界面提供。但是,SampleCustomer
类不会从其接口继承成员。该规则没有改变。为了调用在接口中声明和实现的任何方法,该变量必须是接口的类型,在此示例中为ICustomer
。
That cast from
SampleCustomer
toICustomer
is necessary. TheSampleCustomer
class doesn't need to provide an implementation forComputeLoyaltyDiscount
; that's provided by theICustomer
interface. However, theSampleCustomer
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#接口默认方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!