编译器看不到接口的默认实现? [英] Default implementation in interface is not seen by the compiler?

查看:81
本文介绍了编译器看不到接口的默认实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在ac#项目中的一个代码,该项目针对Visual Studio 2019(16.3.9)的.NET Core 3.0(因此我应该在C#8.0中)

Here is a my code inside a c# project that targets .NET Core 3.0 (so I should be in C# 8.0) with Visual Studio 2019 (16.3.9)

public interface IJsonAble
{
    public string ToJson() => System.Text.Json.JsonSerializer.Serialize(this);
}

public class SumRequest : IJsonAble
{
    public int X { get; set; }

    public int Y { get; set; }

    public void Tmp()
    {
        new SumRequest().ToJson(); //compile error
    }
}

编译错误为:


CS1061'SumRequest'不包含'ToJson'的定义,并且没有可访问的扩展方法'ToJson'接受类型为'SumRequest'的第一个参数可以找到(您是否缺少using指令或程序集引用?)

CS1061 'SumRequest' does not contain a definition for 'ToJson' and no accessible extension method 'ToJson' accepting a first argument of type 'SumRequest' could be found (are you missing a using directive or an assembly reference?)

有人可以阐明这种行为吗?

Can someone shed some light on this behavior ?

推荐答案

方法仅在接口上可用,而在 class 上不可用。因此,您可以改为:

Methods are only available on the interface, not the class. So you can do this instead:

IJsonAble request = new SumRequest()
var result = request.ToJson();

或:

((IJsonAble)new SumRequest()).ToJson();

原因是它允许您添加到界面中而不必担心下游后果。例如, ToJson 方法可能已经存在于 SumRequest 类中,您希望它被调用吗?

The reason for this is it allows you to add to the interface without worrying about the downstream consequences. For example, the ToJson method may already exist in the SumRequest class, which would you expect to be called?

这篇关于编译器看不到接口的默认实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆