关于在Java中运行但在C#中不运行的接口的问题。

huangapple go评论67阅读模式
英文:

A question about interfaces that run on Java but not in C#

问题

我有一个在Java上运行且没有任何错误的服务层结构。但是当我尝试在C#上运行时,它并不像我预期的那样工作。我有一个通用的服务接口 IService,其中有一个返回另一个接口 IUpdateResult 的方法 Update。我还有一个自定义的服务接口 IAService,如下所示。

public interface IService 
{
    IUpdateResult Update();
}

public interface IAService : IService 
{     

} 

最后,我有一个实现了 IUpdateResultUpdateResult 类。

public class UpdateResult : IUpdateResult
{
}

我正在实现自定义的服务类,如下所示,但它不允许我这样做。

public class AService : IAService
{
    public UpdateResult Update()
    {
        // 哔哔
    }
}

正如我所提到的,在Java上它按照我想要的方式工作。为什么C#会给我报错呢?

英文:

I have a service layer structure works on Java without any error. But when I try it on C# it's not working as I expected. I have a common service interface IService which has a method Update that returns another interface IUpdateResult. And I have a custom service interface IAService like below.

public interface IService 
{
    IUpdateResult Update();
}

public interface IAService : IService 
{     

} 

And finally I have a UpdateResult class which implements IUpdateResult.

public class UpdateResult : IUpdateResult
{
}

I am implementing custom service class like below and it does not allow me to do this.

public class AService : IAService
{
    public UpdateResult Update()
    {
        // bla bla
    }
}

As I mentioned it's working on Java the way I want. Why does C# give me error?

答案1

得分: 4

> 正如我所提到的,它在Java上按照我想要的方式运行。为什么C#会给我错误?

因为Java和C#是不同的编程语言,由不同团队设计开发的。:)

不用担心,正如评论所说,这个特性计划在C# 9中实现

目前可以使用显式接口实现

public class AService : IAService
{
    public UpdateResult Update()
    {
        return null;
    }
    
    IUpdateResult IService.Update() { return Update(); }
}
英文:

> As I mentioned it's working on Java the way I want. Why does C# give me error?

Because Java and C# are different languages, designed by different teams of people. 关于在Java中运行但在C#中不运行的接口的问题。

Don't worry, as the comments said, this feature is planned for C# 9.

For now, you can use an explicit interface implementation:

public class AService : IAService
{
    public UpdateResult Update()
    {
        return null;
    }
    
    IUpdateResult IService.Update() { return Update(); }
}

huangapple
  • 本文由 发表于 2020年10月8日 16:09:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64258363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定