我想将不同类型的列表添加到列表中。这是我的方法:
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>
.我也尝试过使用模板,但我没有让它运行。
最佳答案
使用 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
摘要:
If you use dynamic you're opting into dynamic typing, and thus opting out of compile-time checking for the most part.
所以这意味着 dynamic
类型将在运行时计算,它并不意味着“任何类型”,它意味着“在运行时定义的某种类型”
关于c# - 不同类型的列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236747/