i want do some action if value of property in object is equal something.
My object:
//abstract class Tile.cs
namespace DungeonGame.Tiles
{
public abstract class Tile
{
public abstract string Type { get; set; }
}
}
//Item.cs that iherits from Tile.cs
namespace DungeonGame
{
public class Item : Tile
{
public override string Type { get; set; }
public string Name { get; set; }
public Item(string name)
{
this.Type = "item";
this.Name = name;
}
}
}
And i have several objects in public Object[,] BoardTiles { get; private set; }
, I had to store different types of tiles in same place so i had to use Object type array.
What i'm trying to do is replace array index with different type of object, depending of the value of property (In this case I set value depending of object type not his value of property):
public void movefillRight(int playerPositionRowIndex, int playerPositionColumnIndex)
{
for (int r = 0; r < Rows; r )
{
for (int c = 0; c < Cols; c )
{
if (BoardTiles[playerPositionRowIndex, playerPositionColumnIndex ].GetType().ToString() == ("DungeonGame.Item"))
{
/* placePlayerOnTheBoard(playerPositionRowIndex, playerPositionColumnIndex, PlayerTile);
*/ BoardTiles[playerPositionRowIndex, playerPositionColumnIndex] = Item1;
BoardTiles[playerPositionRowIndex, playerPositionColumnIndex - 1] = Floor;
}
else if (BoardTiles[playerPositionRowIndex, playerPositionColumnIndex-1].GetType().ToString() == ("DungeonGame.Item"))
{
BoardTiles[playerPositionRowIndex, playerPositionColumnIndex-1] = Item1;
placePlayerOnTheBoard(playerPositionRowIndex, playerPositionColumnIndex, PlayerTile);
}
else
{
placePlayerOnTheBoard(playerPositionRowIndex, playerPositionColumnIndex, PlayerTile);
BoardTiles[playerPositionRowIndex, playerPositionColumnIndex - 1] = Floor;
}
}
}
Console.WriteLine(BoardTiles[playerPositionRowIndex, playerPositionColumnIndex].GetType().ToString());//log
}
The functionality of the function is to leave the same object on the same index when the player walks over it, so the problem is that code is ok when I have one Item, for example only sword, but when there are more items i can replace index always with same object but not with object witch different properties, when the player walks over a good sword and bad sword (same object, but another properties) he leave behind just sword... I have idea how to solve this problem but i need to refer to property value which is at specific index of my object array.
CodePudding user response:
After you check that the item in the array is of a specific type you can then cast it.
if (BoardTiles[playerPositionRowIndex, playerPositionColumnIndex ].GetType().ToString() == ("DungeonGame.Item"))
{
var item = (DungeonGame.Item)BoardTiles[playerPositionRowIndex, playerPositionColumnIndex];
Console.Writeline(item.Name);
}