如何强制派生类实现静态属性或字段? [英] How to force derived class to implement a static property or field?

查看:123
本文介绍了如何强制派生类实现静态属性或字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的抽象类:

abstract class Enemy
{
    protected static abstract float HEALTH
    {
        get;
    }

    float health;

    void someMethod()
    {
        health = HEALTH;
    }
}

这是我的派生类:

abstract class BadGuy : Enemy
{
    protected override static float HEALTH
    {
        get { return 1; }
    }
}

先生.编译器说我不能在Enemy类中使成员HEALTH既静态又抽象.

Mr. Compiler says I can't make the member HEALTH static as well as abstract in the Enemy class.

我的目标是强制每个子类具有一个可以从父类访问的静态或常量字段.

My goal is to force each child class to have a static or constant field which can be accessed from the parent class.

有解决方案吗?如果没有,最优雅的解决方法是什么?使属性变为非静态?

Is there a solution for this? If not, what's the most elegant workaround? Making the property non-static?

推荐答案

static和继承不能一起使用.您可以做的是创建一个虚拟属性,该属性可以在派生类中被覆盖.如果愿意,可以在Enemy中提供基本的实现,或者如果不想,可以将其保留为abstract:

static and inheritance don't work together. What you can do is make a virtual property which can be overridden in the derived class. If you wish, you can either provide a base implementation inside Enemy, or keep it abstract if you don't want to:

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; }
    }
}

这篇关于如何强制派生类实现静态属性或字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆