<分区>
我想要一个泛型类型的列表(实际上我只需要字符串和整数)。两个对象都有名称(字符串)但值不同(整数或字符串)
public class Setting
{
public string Name { get; set; }
}
public class Setting<T> : Setting
{
public T Value { get; set; }
public Type Type
{
get
{
return typeof(T);
}
}
}
名单如下:
List<Setting> list = new List<Setting>();
list.Add(new Setting<int> { Name = "one", Value = 10 } );
list.Add(new Setting<string> { Name = "two", Value = "string value" });
但是,当我尝试获取该值时,它不存在。
list[0].Value ????
这可以做到吗?
编辑:
令人惊讶的是它是如此简单(与泛型、接口(interface)相比),感谢@Patrick Hofman 的“对象”提示。
public class Settings
{
public string Name { get; set; }
public object Value { get; set; }
}
Fields = new List<Settings>{
new Settings { Name = "Three", Value = "Three_value" },
new Settings{ Name = "Four", Value = 22 },
new Settings { Name = "Two", Value = "22" }
}
像魅力一样工作。