Gui*_*lho 2 c# inheritance properties interface unity-game-engine
我想在一个类中实现以下接口:
public interface IAgro {
AgroState agroState { get; }
}
Run Code Online (Sandbox Code Playgroud)
问题是,我希望我的属性实现从 AgroState 继承的不同类,而不是使用接口在类中实现 AgroState
public class E1_AgroState : AgroState
{
...
}
public class BasicWalkingEnemy : Entity, IAgro
{
public E1_AgroState agroState { get; }
}
Run Code Online (Sandbox Code Playgroud)
例如,这是我习惯在 Swift 中使用协议做的事情,但是 C# 编译器抱怨
“BasicWalkingEnemy”未实现接口成员“IAgro.agroState”。“BasicWalkingEnemy.agroState”无法实现“IAgro.agroState”,因为它没有匹配的“AgroState”返回类型。[Assembly-CSharp]csharp(CS0738)
现在我发现的一种解决方案是这样做:
public class BasicWalkingEnemy : Entity, IAgro
{
public AgroState agroState { get { return _agroState; } }
public E1_AgroState _agroState { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
但我认为这是非常不优雅的。我的问题有更好的解决方案吗?
通常,您执行此操作的方式是使用显式接口实现,以便任何只知道您的对象 via 的人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; }
}
Run Code Online (Sandbox Code Playgroud)