Is there a way to ensure that a static member exists in a child class in C #?

For a tile-based game, I use different classes to describe the behavior of different types of tiles. They (obviously) follow from the base class. Now I have a problem that sometimes I need to find out if a player has enough funds to pay for updating to a certain type of tile.

Since the cost of the type of tile remains the same all the time, it seems to make sense to make it static. Unfortunately, C # does not seem to allow the use of abstract classes or interfaces to ensure the existence of such a static field in a child class.

My โ€œsolutionโ€ was to get this data using reflection, but it seems pretty ugly and potentially dangerous to me, because I can forget the static field in one of the child classes, which will destroy it all ...

The following code snippet is what I have; AllowedUpdatesis one List<System.Type>containing types that can be upgraded to.

foreach (Type t in AllowedUpdates) {

    // Get the Action Point Cost
    FieldInfo fi = t.GetField ("actionPointCost", BindingFlags.NonPublic | BindingFlags.Static);
    int cost = (int)fi.GetValue (null);

    // Check for any requirements
    bool requirementsFulfilled;
    try {
        // Get the static method that checks the necessary requirements.
        MethodInfo mi = t.GetMethod ("CheckRequirements", new Type[] { typeof(Dictionary<string, ProtoObject>) });
        object[] arguments = { neighbourFields };

        // Invoke this method
        object returnValue = mi.Invoke (null, arguments);
        requirementsFulfilled = (bool)returnValue;
    } catch (ArgumentNullException) {
        // This type has no special requirements, pass it.
        requirementsFulfilled = true;
    } catch (NullReferenceException) {
        // No requirements needed, pass it.
        requirementsFulfilled = true;
    }
}

There must be a better way to do this. Do I have a design template?

+5
source share
5 answers

You cannot use either an abstract base class or an interface, the existence of a member staticin any derived class.

- . static. abstract . .

public abstract int ActionPointCost { get; }
+6

, . , / ( , , ). Dictionary<Tile, int>, .

0

refactor , , ..

0

. Interfaces Abstract classes .

, , . Eric Lippert, .

, , , , Reflection . , , , .

post-build action , Code Contracts do.

0

, , , .

, - , ", ", .

Make this read-only instance field that must be specified by the constructor. Seriously, you'll get rid of your headache.

0
source

All Articles