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

问题描述

这是我在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
    }
}

编译错误为:

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

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?

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

08-05 16:27