Default implementation in interface is not seen by the compiler?

后端 未结 2 1488
野趣味
野趣味 2020-12-06 19:19

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
{
            


        
相关标签:
2条回答
  • 2020-12-06 19:24

    Try using (new SumRequest() as IJsonAble).ToJson(); to help the compiler a bit.

    Anyway, I'm sure what you're after is (this as IJsonAble).ToJson(), assuming you want to apply ToJson on current SumRequest instance.

    0 讨论(0)
  • 2020-12-06 19:46

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

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

    Or:

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

    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?

    0 讨论(0)
提交回复
热议问题