开发者

Accessing the right member based on the object type

PlayerBase is a base class for FieldPlayer and GoalKeeper. I have stateMachine memeber in FieldPlayer and GoalKeeper. But in MyList a FieldPlayer and a GoalKeeper are both treated as PlayerBase. How do I make sure that I get the stateMachine for the right type? Should 开发者_Go百科I somehow check for type and then typecast?

foreach (PlayerBase p in MyList)
{
 // Here I need to access p.stateMachine for FieldPlayer or GoalKeeper, depends what p is.
}

Thanks


The member should be declared in PlayerBase as a property. Perhaps this is an abstract declaration, or at the least a virtual declaration. The property could then be overriden in your derived classes if they need something other than the default behavior.

abstract class PlayerBase
{
    public abstract TheType StateMachine { get; set; }  // declare here

    // if PlayerBase is not abstract, you can declare the property as: 
    // public virtual TheType StateMachine { get; set; }
}

class FieldPlayer : PlayerBase 
{
    public override TheType StateMachine { get; set; } // implement here
}

You typically don't want to be in the position of doing type-checking in code that deals with the base type. More specified (or derived) types should be able to be directly substituted for the base without the code caring.


foreach (PlayerBase p in MyList)
{
    var fp = p as FieldPlayer;
    if (fp != null)
    {
        // p is a FieldPlayer => you can access the stateMachine property
        Console.WriteLine(fp.stateMchine);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜