I'm creating a game, and am currently working on the Inventory system for it. I have a class to represent the player, which looks like this:
class Player {
public Weapon WeaponSlot {get;set;}
public Shield ShieldSlot {get;set;}
//etc.
}
Weapon, Shield, etc are subclasses of a generic Item class:
class Item {
//...
}
class Weapon : Item {
//...
}
There are subclasses of Weapon, etc, but that's not important.
Anyway, I am creating a UserControl to display/modify the contents of a given inventory slot. However, I'm not sure exactly how to do that. In C++, I would use something like:
new InventorySlot(&(player.WeaponSlot));
But, I can't do that in C#.
I found the TypedReference struct, but that doesn't work since you are not allowed to make a field with one of those structs, so I couldn't store it for use later in the control.
Is reflection the only way to go, or is there some other facility that I'm not aware of?
EDIT ----
For reference, here's what I've done:
partial class InventorySlot : UserControl {
PropertyInfo slot;
object target;
public InventorySlot(object target, string field) {
slot = target.GetType().GetProperty(field);
if (!slot.PropertyType.IsSubclassOf(typeof(Item)) && !slot.PropertyType.Equals(typeof(Item))) throw new //omitted for berevity
this.target = target;
InitializeComponent();
}
//...
}
And, it's initialized like this:
new InventorySlot(player, "WeaponSlot");
Also, regarding performance, I'm not too concerned about that. It's not a real-time game, so I only have to update the screen in response to player actions. :)