I created an interface and generic class implementing that interface, so that object of the same class can hold any type of data. I created list of it successfully. But how to read data from list in type safe manner.
public interface Parameter
{
}
public class Parameter<T> : Parameter
{
public T Value { get; set; }
}
Parameter[] parameters = new Parameter[] {
new Parameter<string> { Value = "X" },
new Parameter<int> { Value = 1 },
};
How should I loop through array and get individual value? Parameter interface has no declaration of property Value.
You can declare a property of type Object
in the Parameter
interface; this will allow you to access the value, whatever its actual type:
public interface Parameter
{
object Value { get; set; }
}
public class Parameter<T> : Parameter
{
public T Value { get; set; }
// Explicit interface implementation
object Parameter.Value
{
get { return Value; }
set { Value = (T)value; }
}
}
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.