c# - BaseClass method which returns an arbitrary subclass of BaseClass -
in game have base class of loot has methods universal can picked player , stored in inventory. include potions, equipment, ammo, etc. can equip arrows, not potions. arrow subclass of ammo, derive loot. can drink potion not arrow. potion subclass loot implement iconsumeable. , on.
loot objects have quantity property (10 arrows; 2 potions). in loot class have method called split allows player take "stack" of items (like arrows) , split 2 separate stacks. decreases arrow instance's quantity amount, returns new arrow instance quantity value = taken original instance.
my idea i'd write method in loot since loot can stacked long int stacklimit property greater 1. after decrementing calling loot quantity specified, i'd return new object of same type. problem is, don't know type of loot subclass object be.
public abstract class loot { public int quantity { get; set; } public loot split(int quantitytotake) { loot clone = (loot)this.memberwiseclone(); //restrictnumbertorange(int min, int max, int value) delegate clamps value min,max this.quantity -= utility.restrictnumbertorange<int>(1, this._quantity - 1, quantitytotake); clone.quantity = quantitytotake; return clone; } }
is poor way go this? thought reflection, hear mixed opinions on whether or not use in case this.
is there no way define method deal this.furthestsubclass?
i know subclasses may have different constructors, it's not feasible try , return 'new this.furthestsubclass()' because can't know how construct it. i'd able deal loot methods, i'm using loot return type.
i think case generics. try rewriting split method in loot this:
public tloot split<tloot>(int quantitytotake) tloot : loot { tloot clone = (tloot)this.memberwiseclone(); ... return clone; }
that ought take care of typing issues.
edit add: constructor issue bit more interesting, may find parameterless constructors useful, in combination object initalizers. if modify constraint follows:
public tloot split<tloot>(int quantitytotake) tloot : loot, new(tloot) { // stuff tloot newloot = new tloot(); ... return newloot; }
the "new(t)" constraint allows create new objects based on generic type.
further edit: should give example of object initializer in context:
tloot newloot = new tloot { quantity = quantitytotake };
this assumes loot has public property called quantity. object initializers can set values public property has public set{};
Comments
Post a Comment