我想在类中实现以下接口(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/