c# - 不同类型的列表列表

标签 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> .我也尝试过使用模板,但我没有让它运行。

最佳答案

使用 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/

相关文章:

c# - Hangfire 单实例重复作业

c# - 如何防止 WCF 服务进入故障状态?

jQuery 对话框回发但 UpdatePanel 未更新

python - 从python中的字典列表构造两个列表

具有嵌套列表/元组的 Python 操作(交集、联合、重复)可能吗?

python - 从 Python 列表中删除坐标

c# - SQL 服务器 2008 : BeginExecuteNonQuery/EndExecuteNonQuery Problem

C# AES Base64 加密(字符串)

c# - 在 Entity Framework Code First 中忽略基类型是否也会忽略子类?

.Net 核心和插件