簡體   English   中英

無法確定條件表達式的類型,因為'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? ,因此編譯器會對您大吼大叫。 這是假設.Agesint? ,否則應.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM