'How to force derived class to implement a static property or field?
This is my abstract class:
abstract class Enemy
{
protected static abstract float HEALTH
{
get;
}
float health;
void someMethod()
{
health = HEALTH;
}
}
This is my derived class:
abstract class BadGuy : Enemy
{
protected override static float HEALTH
{
get { return 1; }
}
}
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?
Solution 1:[1]
Something very similar to the question's original implementation is now possible starting with C#10, by using static abstract members in an interface:
public interface IEnemy
{
public static abstract float Health { get; }
public float GetHealth()
{
return (float)GetType().GetProperty(nameof(Health)).GetValue(null);
}
}
public class BadGuy : IEnemy
{
public static float Health => 1f;
}
Implementation beyond this will vary somewhat depending on use, however if one desires to maintain a generic Enemy class in a similar form to that of the original question then one of the ways this could be done is as follows*:
public class Enemy
{
private float health;
public void SetEnemy(IEnemy enemy)
{
health = enemy.GetHealth();
}
}
*Better options almost certainly exist, but again, they will vary based on intended use.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pikanchion |
