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) {
FieldInfo fi = t.GetField ("actionPointCost", BindingFlags.NonPublic | BindingFlags.Static);
int cost = (int)fi.GetValue (null);
bool requirementsFulfilled;
try {
MethodInfo mi = t.GetMethod ("CheckRequirements", new Type[] { typeof(Dictionary<string, ProtoObject>) });
object[] arguments = { neighbourFields };
object returnValue = mi.Invoke (null, arguments);
requirementsFulfilled = (bool)returnValue;
} catch (ArgumentNullException) {
requirementsFulfilled = true;
} catch (NullReferenceException) {
requirementsFulfilled = true;
}
}
There must be a better way to do this. Do I have a design template?
source
share