c# - 对象列表中的动态数据类型

标签 c# asp.net

List<object> list = new List<object>();

long foo = 1;
List<long> bar = new List<long>(){ 1,2,3 }; 

bool someBool = false;

list.Add(new { someProp = someBool ? foo : bar });

为什么不能someProp数据类型动态?数据类型未指定为对象键,因此我看不到问题。

There is no implicit conversion between long and List<long>

最佳答案

错误是因为 conditional operator (也称为三元运算符) ? .假定返回单一类型对象,因为longList<long>是不同的。你得到了错误。

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

一个最简单且更具可读性的替代方案(IMO)是:

if (someProp == someBool)
    list.Add(new { someProp = foo });
else
    list.Add(new { someProp = bar });

但是上面两个就不一样了Anonymous type对象。

或者您可以去掉 Anonymous 对象并简单地将两者添加到列表中,因为它是 List<object>喜欢:

if (someProp == someBool)
    list.Add(foo);
else
    list.Add(bar);

关于c# - 对象列表中的动态数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16708050/

相关文章:

c# - 类型为 'System.NullReferenceException' 的第一次机会异常发生在 Unknown Module-mvc custom authentication

c# - 如何使用基于 QueryString 的 ASP.NET ObjectDataSource 检索数据?

c# - 删除最后一行以外的任何行后,如何对自动增量列值重新排序?

asp.net - 根据静态控件的选定值创建动态控件

c# - 如何使用此枚举列表减少代码

c# - 调用存储过程 SQL

c# - Azure SDK 1.4 - WIF - 尝试初始化默认应用程序域时,C++ 模块无法加载

C# 方法返回与 lambda 中的变量

c# - OwnerDrawnElement 背景颜色为黑色,直到被选中

c# - 将页眉和页脚图像添加到 PDF : Header image doesn't show, 页脚被放大