c# - C#接口(interface)和继承的问题

标签 c# unity3d inheritance interface properties

我想在类中实现以下接口(interface):

public interface IAgro {
     AgroState agroState { get; }
}

问题是,我希望我的属性实现一个继承自 AgroState 的不同类,而不是使用接口(interface)在类中实现 AgroState

public class E1_AgroState : AgroState
{
...
}

public class BasicWalkingEnemy : Entity, IAgro
{
    public E1_AgroState agroState { get; }

}

例如,这是我在 Swift 中使用协议(protocol)所做的事情,但是 C# 编译器提示

'BasicWalkingEnemy' does not implement interface member 'IAgro.agroState'. 'BasicWalkingEnemy.agroState' cannot implement 'IAgro.agroState' because it does not have the matching return type of 'AgroState'. [Assembly-CSharp]csharp(CS0738)

目前我发现的一种解决方案是:

public class BasicWalkingEnemy : Entity, IAgro
{
    public AgroState agroState { get { return _agroState; } }
    public E1_AgroState _agroState { get; private set; }
}

但我认为那很不优雅。 我的问题有更好的解决方案吗?

最佳答案

通常,您执行此操作的方式是使用显式接口(interface)实现,这样任何只通过IAgro 了解您的对象的人都只会看到AgroState,但任何知道它正在与 BasicWalkingEnemy 一起工作的代码都将获得 E1_Agrostate:

// Note: property names changed to comply with .NET naming conventions
public class BasicWalkingEnemy : Entity, IAgro
{
    // Explicit interface implementation
    AgroState IAgro.AgroState => AgroState;

    // Regular property
    public E1_AgroState AgroState { get; private set; }
}

关于c# - C#接口(interface)和继承的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62209388/

相关文章:

c# - 确保用户只能保存在文件夹内

c# - 如何在winform中制作默认的照片查看器或文本编辑器等

c# - 帮助在 C# .Net 中设置 RTSP 流服务器

c# - 如何停止默认动画?

C# - 将类的新实例添加到数组

c# - 我在 C# 中有一个 for 循环我只想运行一次

c++ - 继承 std::stack 会导致 clang 出错,但适用于 gcc

c# - 如何有条件地使用 MVC Controller 注释

php - Symfony 2 + Doctrine 2 + 继承

c# - 调用多个类类型列表中的特定类函数