Good! I have 3 classes, one is TokenBase
, which is used as parent of the other classes:
abstract class TokenBase
{
public TokenTypes Type { get; set; }
public virtual object Value { get; set; }
public override string ToString()
{
return $"Type: {Type}\t\t Value: {Value}";
}
}
Derived classes:
class StringToken : TokenBase
{
private string _Value;
public new string Value
{
get { return _Value; }
set { _Value = value;}
}
public StringToken(string v) { Type = TokenTypes.String; Value = v; }
}
class SymbolToken : TokenBase
{
private string _Value;
public new Symbols Value
{
get { return _Value; }
set { _Value = value;}
}
public SymbolToken(Symbols v) { Type = TokenTypes.Symbol; Value = v; }
}
The problem lies when I want to call ToString()
o Value
on one of the derived classes inside the list:
public static void Main(string[] args)
{
IList<TokenBase> Tokens = new List<TokenBase>();
Tokens.Add(new StringToken("Hola Mundo"));
foreach (TokenBase T in Tokens)
{
Console.WriteLine(T.ToString());
// Obtengo la siguiente salida: "Type: String Value: "
Console.WriteLine(T.Value.ToString()); // Obtengo: ""
}
Console.ReadLine();
}
// Salida esperada: "Type: String Value: Hola Mundo"
How can I directly access the property Value
of one of the derived types?
But you do not need to do what you propose, by defining the property as virtual it has an implementation for the child classes that you could override, but in this case it is not necessary
if you define
you can from the child classes assign the properties of the base
Also if you define a property as virtual you are supposed to use the override
If the behavior must change then you would do the following
If you change your class
StringToken
to the following, your example should work:Or if you want to keep your property
Value
of typeString
, you can do something like this: