从实现类调用C#接口默认方法

编程入门 行业动态 更新时间:2024-10-26 21:20:44
本文介绍了从实现类调用C#接口默认方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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#接口默认方法

本文发布于:2023-11-15 21:16:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598026.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!