不同类型的列表列表

时间:2015-10-20 12:31:24

标签: c# .net list

我想将不同类型的列表添加到列表中。这是我的方法:

struct Column
{
    public string title;
    public List<dynamic> col;
}

var signals = new List<Column>();
signals.Add(new Column {title = "stringCol", col = new List<string>() });
signals.Add(new Column {title = "doubleCol", col = new List<double>() });

它表示List<string>无法转换为List<dynamic>。我也尝试过使用模板,但我没有让它运行。

1 个答案:

答案 0 :(得分:6)

使用object代替dynamic,您将获得object的列表,您可以将其转换为所需的类型。

struct Column
{
    public string title;
    public List<object> col;
}

var signals = new List<Column>();
signals.Add(new Column {title = "stringCol", col = new List<object> {new List<string>() }});
signals.Add(new Column {title = "doubleCol", col = new List<object> {new List<double>() }});

为什么不动态?在这里阅读:dynamic vs object type

摘要:

  

如果你使用动态,你会选择动态打字,从而选择   大部分时间没有编译时检查。

所以它意味着dynamic类型将在运行时计算,它并不意味着“任何类型”,它意味着“在运行时定义的某种类型”

相关问题