2016-06-28 60 views
-1

我有这行代码:无法确定条件表达式的类型,因为'int?'之间没有隐式转换。和“串”

Ages = m.RelatedMultipleWorks.Count == 0 ? 
     m.RelatedLook.Age: m.RelatedLook.Age.ToString() + " | " + 
          m.RelatedMultipleWorks. 
          Select(z => z.RelatedLook.Age.ToString()). 
          Aggregate((current, next) => current + " | " + next) 

此行被赋予此错误:

Type of conditional expression cannot be determined because there is no implicit conversion between 'int?' and 'string' 

我不明白为什么我得到这个错误。我怎样才能摆脱它?谢谢。

+2

只需在第一个'm.RelatedLook.Age'之后添加一个'ToString'。 – juharr

+0

你想要什么类型的“年龄”? 'm.RelatedLook.Age'是一个'int?',而'm.RelatedLook.Age.ToString()...'是一个'string'。 – haim770

+0

在表达式的同一部分中,根据条件,您曾经分配过一个“int”和“string”,这是不可能的。你应该添加'.TosTring()'到第一个年龄段或者从第二个年龄段中删除它。取决于你的“年龄”是什么类型。 –

回答

1

三元运算符期望两个输出具有相同的类型。使用以下内容:

Ages = m.RelatedMultipleWorks.Count == 0 ? m.RelatedLook.Age.ToString(): m.RelatedLook.Age.ToString() + " | " + m.RelatedMultipleWorks.Select(z => z.RelatedLook.Age.ToString()).Aggregate((current, next) => current + " | " + next), 
1

您的m.RelatedLook.Age大概是int?,但由于.Aggregate,二级三元表达式的结果是string

Ages(推测)预计int?;三元组的后半部分不能被隐含地转换为int?,所以编译器向你大喊。这是假设.Agesint?,否则你应该检查m.RelatedLook.Age.ToString()的结果。

虽然声音有点臭,但作为一个字符串存储Ages - 考虑可能使用IEnumerable<int>而不是?

我最初走近这个答案试图解释,也许Ages类型是不正确的,但我要解释一下,这是因为发生三元无法解析这两个字符串诠释?因为这些类型不相同。只要ToString在第一个年龄段将修复编译器错误。

+1

实际上问题是条件运算符的两部分不匹配,并且没有共同的隐式转换。一旦这个问题得到解决,那么无论什么类型的“年龄”都可能存在转换问题,但这不是错误信息的含义。 – juharr

+0

这就是我的意思,但我没有很好地解释它。我会补充说;谢谢。 –

+0

是的,我想将'Ages'作为一个字符串存储,为什么我需要'IEnumerable '?谢谢。 – jason

相关问题