C#接口和继承的问题
Problem with C# interfaces and inheritance
我想在 class 中实现以下接口:
public interface IAgro {
AgroState agroState { get; }
}
问题是,我希望我的 属性 实现一个继承自 AgroState
的不同 class,而不是使用接口在 class 中实现 AgroState
public class E1_AgroState : AgroState
{
...
}
public class BasicWalkingEnemy : Entity, IAgro
{
public E1_AgroState agroState { get; }
}
例如,这是我在 Swift 中使用协议所做的事情,但是 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; }
}
但我认为那很不雅观。
我的问题有更好的解决方案吗?
通常你这样做的方式是使用 显式接口实现 这样任何只通过 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; }
}
我想在 class 中实现以下接口:
public interface IAgro {
AgroState agroState { get; }
}
问题是,我希望我的 属性 实现一个继承自 AgroState
的不同 class,而不是使用接口在 class 中实现 AgroStatepublic class E1_AgroState : AgroState
{
...
}
public class BasicWalkingEnemy : Entity, IAgro
{
public E1_AgroState agroState { get; }
}
例如,这是我在 Swift 中使用协议所做的事情,但是 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; }
}
但我认为那很不雅观。 我的问题有更好的解决方案吗?
通常你这样做的方式是使用 显式接口实现 这样任何只通过 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; }
}