I want to make a list of allowed to create magic by my player, and I want to protect the list from accidentally writing an object there that is not inherited from the Magic class.
class Magic
{
...
}
class FireBall: Magic
class IceBall: Magic
class Player
{
List<...> magicAllowedForSpawning;
}
CodePudding user response:
You can do simply List<Magic>
and add the childs here, but then you only can use base props, if you want to use specific property you must cast this item to specific class that you want
CodePudding user response:
why not simply use List ?. you can add both Fireball and Iceball objects to List of Magic class.
class Magic
{
}
class FireBall: Magic
{}
class IceBall: Magic
{}
class Player
{
public List<Magic> magicAllowedForSpawning;
public List<FireBall> GetFireballs()
{
var fireBalls = magicAllowedForSpawning.Where((a) => a.GetType() == typeof(FireBall)).Select(x=> (FireBall)x).ToList();
return fireBalls;
}
public void AddFireball(FireBall b){
magicAllowedForSpawning.Add(b);
}
public void AddIceball(IceBall b){
magicAllowedForSpawning.Add(b);
}
}