I have classes/interfaces similar to the following:
public interface IValueToken
{
}
public abstract class ProgramToken
{
public ProgramToken(string name)
{
Name = name;
}
public string Name { get; }
}
public class ValueToken<T> : ProgramToken, IValueToken
{
public ValueToken(string name, T value) : base(name)
{
Item = value;
}
T Item { get; }
}
There are different generic ValueToken<T>
types and they are held in a List<ProgramToken>
, along with other types derived from ProgramToken
I need to do similar to this:
var token = new ValueToken<int>("int", 78);
if (token is IValueToken ivt)
{
var value = ivt.Value;
// do something with value
....
}
Some posts here at SO mentioned doing similar to how List does it, implementing the non-generic interface explicitly. I thought it was something like this:
Change IValueToken
to
public interface IValueToken
{
object Item { get; }
}
and ValueToken to
public class ValueToken<T> : ProgramToken, IValueToken
{
public ValueToken(string name, T value) : base(name)
{
Item = value;
}
object IValueToken.Item { get { return (T)Item; } }
T Item { get; }
}
But this isn't working the same as List<T>
. It returns an object
type.
What am I doing wrong? Or what is a better way of accomplishing this?