2016-05-30 55 views
3

在C#我可以分配一個號碼(最多255)直接連接到類型字節的變量:如果我這樣做在一個更復雜的聲明與一個條件運算爲什麼在使用條件運算符時需要額外的投射?

byte red = 255; 

然而:

byte red = (redNode != null) ? byte.Parse(redNode.Value) : 255; 

我得到一個錯誤:「CS0266不能隱式地將類型'int'轉換爲'byte'。存在明確的轉換(你是否缺少一個轉換?)」。

我需要明確地做投以字節爲255:

byte red = (redNode != null) ? byte.Parse(redNode.Value) : (byte)255; 

這是爲什麼投需要?

+0

因爲兩者如果其他人應該返回相同類型的實例 –

+0

那裏不是從int到byte的隱式轉換,而是明確的轉換。由於某種原因,它被命名爲「顯式」 - 您需要明確地應用它:) – Evk

回答

3

C#中的數字文字是int,而不是byte。嘗試0xff

no implicit conversion from int to byte,第一條語句byte red = 255;是一個特殊情況。

A constant expression of type int can be converted to sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant expression is within the range of the destination type.

這並不能解釋爲什麼它不轉換常數255的第二表達式,不是嗎?

它不需要在第二個表達式中轉換255,因爲there is an implicit conversion from byte to int。因此byte.Parse(redNode.Value)轉換爲int。因此,(redNode != null) ? byte.Parse(redNode.Value) : 255;的類型爲int - 並且因爲它不是一個常量表達式,所以不會再隱式轉換爲byte

你認爲錯誤消息,要求你要做到這一點:

byte red = (redNode != null) ? byte.Parse(redNode.Value) : (byte)255; 

,但它確實是問你要做到這一點:

byte red = (byte)((redNode != null) ? byte.Parse(redNode.Value) : 255); 
+0

問題的關鍵在於爲什麼它在這種情況下不起作用,但是在進行直接分配時起作用。 – ChrisF

+1

但是爲什麼它與第一個作業不同? –

+1

@ stefan.s웃擴大了答案。 – Peter

相關問題