我將 switch 陳述句轉換為運算式和預期值以具有相同的型別。但是,運算式回傳十進制型別而不是 int。
using System;
public class Program
{
public enum SomeType
{
INT32,
DECIMAL
}
public static void Main()
{
_ = Enum.TryParse("INT32", out SomeType paramType);
object? value = null;
//
value = paramType switch
{
SomeType.DECIMAL => (decimal)2.0,
SomeType.INT32 => (int)1,
_ => throw new ArgumentOutOfRangeException($"Not expected type.")
};
Console.WriteLine(value);
Console.WriteLine(value.GetType().ToString());
value = null;
switch(paramType)
{
case SomeType.DECIMAL:
value = (decimal)2.0;
break;
case SomeType.INT32:
value = (int)1;
break;
default:
throw new ArgumentOutOfRangeException($"Not expected type.");
}
Console.WriteLine(value);
Console.WriteLine(value.GetType().ToString());
}
}
結果:
1
System.Decimal
1
System.Int32
這是為什么?你可以在這里試試:https ://dotnetfiddle.net/
uj5u.com熱心網友回復:
switch 運算式試圖找到“最佳”結果型別,就像隱式型別陣列一樣。
給定型別intand decimal,最好的結果型別是,因為雖然有從todecimal的隱式轉換,但只有從to的顯式轉換(因為它會丟失資訊)。intdecimaldecimalint
switch 運算式會將所選“分支”的結果隱式轉換為該型別,而不管它被分配給的變數的型別。
換句話說,您的代碼相當于:
object? value = null;
// The compiler selects tmp here based as the best result type
// between int and decimal
decimal tmp = paramType switch { ... };
// Now the assignment performs any conversions required to assign
// to the variable
value = tmp;
如果您想使 switch 運算式的結果型別object,您需要確保其中一個分支回傳object。例如:
value = paramType switch
{
SomeType.DECIMAL => (object) 2.0m,
SomeType.INT32 => 1,
_ => throw new ArgumentOutOfRangeException($"Not expected type.")
};
(使用 2.0m 只是為了展示一種decimal比投射double值更好的方法......)
現在結果型別是object,并且在您的示例代碼中,您最終會得到一個裝箱int而不是裝箱前int轉換為的值decimal。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474351.html
標籤:C#
上一篇:C#中的物件串列到串列串列
