简体   繁体   中英

Accessing Field from derived Class

I'm trying to access a field from a derived class in an array that holds references to the base class.

I have three classes:

abstract GameObjectBase 
{

}

And derived from that are:

public Gamespace: GameObjectBase
{
     private bool containsItem;
}

And:

public GameWall: GameObjectBase
{
}

(Obviously these classes hold more data, methods, and constructors).

I have created an array from these objects, like this

private GameObjectBase[,] _labyrinthArray = new GameObjectBase[10,10];

I then fill said array with Gamespaces and Gamewalls. But when I access a Gamespace object in the array, the containsItem field is not accessible due to the reference to the object being of type GameObjectBase.

Obviously I could put containsItem in GameObjectBase and make it accessible from there, but that doesn't fit my OOP approach. The only other solution I have found is to cast the object in question explicitely to Gamespace .

That seems quite crude and error prone to me. Is there any better solution to this?

First of all, you cannot reference a private field from outside the object class itself. You probably want to use a read-only property to encapsulate the field. If you don't want to cast the object explicitly to a Gamespace , you could use an interface instead.

public interface ICanContainItem
{
    bool ContainsItem { get; }
}

public class Gamespace : GameObjectBase, ICanContainItem
{
    private bool _containsItem;

    public bool ContainsItem
    {
        get { return _containsItem; }
        private set { _containsItem = value; }
    }
}

This way you can then check whether the object "can contain an item" or not through the interface. Even if in the future you add new types of spaces that can contain an item, this same piece of code works, if the new types also implement the same interface.

var gameObject = _labyrinthArray[i,j]; //i,j defined elsewhere
var mayContainItem = gameObject as ICanContainItem;
if (mayContainItem != null)
{
    var itemExists = mayContainItem.ContainsItem;
    //mayContainItem.ContainsItem = false; //<-- fails because there's no setter
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM