Hi, I’m trying to use the code this.
public static string CreateOptionTooltip(Item item)
{
if(item.getEquipable())
{
string tooltip = "";
EquipmentItem equipItem = (EquipmentItem)item;
for(int i = 0; i < equipItem.optionList.Count; i++)
{
ItemOption option = equipItem.optionList*;*
-
tooltip += option.itemOption.ToString();*
-
if(option.optionAmount >= 0)*
-
tooltip += " +" + option.optionAmount.ToString();*
-
else*
-
tooltip += " -" + option.optionAmount.ToString();*
-
tooltip += "
";*
-
}*
-
return tooltip;*
-
}*
-
else*
-
{*
-
return "";*
-
}*
- }*
The EquipmentItem Class is child class of Item like this.
public class EquipmentItem : Item
{
public EquipmentItem()
{
//Here is initializing code.
}
}
But when I call the method CreateOptionTooltip(Item item) in gaming
there is error
InvalidCast: Cannot cast from source type to destination type
in line
EquipmentItem equipItem = (EquipmentItem)item;
You can only cast up the inheritance tree, you can’t cast down the inheritance tree because not everything is guaranteed to exist.
Say you have a class:
class Foo {
int index;
float position;
}
And another class:
class Bar : Foo {
void Do() {
}
}
Now lets say you are given a variable of type Bar
. This you can easily cast to a Foo
because Bar
inherits from Foo
, ie. you’re casting up the tree. Once you have a Foo
from your Bar
, everything from Foo
still exists in your variable, ie. you have access to index
and position
.
But what if you have a variable of type Foo
. This you cannot cast to a Bar
, simply because a Bar
can Do()
, while a Foo
cannot. Therefore your Foo
cannot be a Bar
, but your Bar
can be a Foo
.
The same goes for the Finger-Thumb analogy. Think of Foo
as a Finger and Bar
as a Thumb. Your Thumb is a finger, ie. you can cast your Thumb to a Finger. But not all Fingers are Thumbs, you therefore cannot cast any Finger to a Thumb.
You therefore cannot cast an Item
to a EquipmentItem
, since not all items are equipment items, but you can cast any EquipmentItem
to an Item
, since all EquipmentItem
s are Item
s.