![](/img/trans.png)
[英]Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'int'
[英]Type of conditional expression cannot be determined because there is no implicit conversion between 'int?' and 'string'
我有這行代碼:
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'
我不明白為什么會收到此錯誤。 我該如何擺脫呢? 謝謝。
您的m.RelatedLook.Age
可能是int?
,但是由於.Aggregate
,二級三元表達式的結果是一個string
。
Ages
(大概)期望一個int?
; 三元的后半部分不能隱式轉換為int?
,因此編譯器會對您大吼大叫。 這是假設.Ages
是int?
,否則應.ToString()
檢查m.RelatedLook.Age
的結果。
但是,將Ages
存儲為字符串聽起來有點臭-考慮使用IEnumerable<int>
代替嗎?
我最初使用此答案是為了解釋Ages
類型可能不正確,但是我應該解釋這是因為三元數不能同時解析為字符串和整數? 因為這些類型不相等。 剛開始使用ToString
就能解決編譯器錯誤。
三元運算符期望兩個輸出為相同類型。 使用以下內容:
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),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.