不同类型的列表列表

Hen*_*ste 3 .net c# 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>() });
Run Code Online (Sandbox Code Playgroud)

它说List<string>无法转换为List<dynamic>.我也试过使用模板,但我没有运行它.

Kam*_*ski 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>() }});
Run Code Online (Sandbox Code Playgroud)

为什么不动态?在这里阅读:动态vs对象类型

抽象:

如果您使用动态您加入到动态类型,从而检查在大多数情况下选择加入的编译时出.

因此,这意味着dynamic类型将在运行时计算,这并不意味着"任何类型"是指"某种类型的在运行时定义"

  • 添加到你的答案我会建议结构中的第三个属性来识别列表的类型.我就像你做的那样回答完全相同:) (2认同)