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 (也称为三元运算符) ?
.假定返回单一类型对象,因为long
和 List<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/