xox*_*xox 1 c# inheritance class-structure
这是我的抽象类:
abstract class Enemy
{
protected static abstract float HEALTH
{
get;
}
float health;
void someMethod()
{
health = HEALTH;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的派生类:
abstract class BadGuy : Enemy
{
protected override static float HEALTH
{
get { return 1; }
}
}
Run Code Online (Sandbox Code Playgroud)
Compiler先生说我不能让成员HEALTH在Enemy课程中保持静态和抽象.
我的目标是强制每个子类具有可以从父类访问的静态或常量字段.
这有解决方案吗?如果没有,最优雅的解决方法是什么?使财产非静态?
static
和继承不能一起工作.你可以做的是创建一个可以在派生类中重写的虚拟属性.如果您愿意,您可以在里面提供基本实现Enemy
,或者abstract
如果您不想要保留它:
public abstract class Enemy
{
protected abstract float Health { get; }
}
public class BadGuy : Enemy
{
private const int BadGuyHealth = 1;
protected override float Health
{
get { return BadGuyHealth; }
}
}
public class EvenWorseGuy : BadGuy
{
private const int WorseGuyHealth = 2;
protected override float Health
{
get { return WorseGuyHealth; }
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1239 次 |
最近记录: |