鉴于以下 interface
使用默认实现:
public interface IState
{
string Name => "Unknown";
}
具体实现如下:
public class Demo: IState
{
public void PrintName()
{
Console.WriteLine(this.Name); // <-- this is invalid syntax
}
}
是否可以从具体类型中调用默认实现?
我查看了 default implementations for C# 8.0 的文档如果答案在那里,我无法发现它。
最佳答案
您可以通过转换 this
来使用它到接口(interface),并调用转换结果的属性。就好像该类使用显式接口(interface)实现来实现该属性一样。这是一个打印“未知”的完整示例:
using System;
public interface IState
{
string Name => "Unknown";
}
public class Demo : IState
{
public void PrintName()
{
Console.WriteLine(((IState) this).Name);
}
}
class Program
{
static void Main()
{
new Demo().PrintName();
}
}
关于C# 8 从具体类型中调用默认实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60043720/