c# - 为什么这个 switch case 返回一个 double,即使它是一个 int?

标签 c# .net-core switch-statement

给定以下代码:

object value = header.DataContentType switch
{
    DataContentType.DOUBLE => (double)BitConverter.ToDouble(currentValueBytes.ToArray()),
    DataContentType.FLOAT => (float)BitConverter.ToSingle(currentValueBytes.ToArray()),
    DataContentType.BYTE => (byte)contentData[i],
    DataContentType.SHORT => (short)BitConverter.ToInt16(currentValueBytes.ToArray()),
    DataContentType.INTEGER => (int)BitConverter.ToInt32(currentValueBytes.ToArray()),
    DataContentType.LONG => (long)BitConverter.ToInt64(currentValueBytes.ToArray()),
    _ => throw new InvalidDataException("Invalid data type"),
};

现在,如果 header.DataContentTypeDataContentType.INTEGER,该值将作为 double 值分配给 value,而不是作为int(int)value 导致 InvalidCastException

如果我进行调试,我可以清楚地看到它进入了 INTEGER 案例,如果我在调试控制台中评估 BitConverter.ToInt32(currentValueBytes.ToArray())我得到一个整数返回。但是,一旦退出 switch case,变量 value 就是 double 类型。

此外,如果我手动执行 value = BitConverter.ToInt32(currentValueBytes.ToArray()) 变量是正确的类型 int。暗示 switch 语句由于某些奇怪的原因必须将类型更改为 double。

我希望 switch case 返回 BitConverter 返回的任何类型。如何让 BitConverter 返回正确 BitConverter 案例的类型?

最佳答案

我很确定如果 switch 表达式中的每个 case 都返回一致的类型,事情会更好。你展示的 Actor 阵容是多余的。每个 BitConverter 调用都会返回您期望的类型。

但是,请记住,这些东西中的每一个最终都会在您的代码中的某个时刻被封装为一个对象。如果您指定装箱发生的时间和方式,可能会更好。考虑这样的事情:

object value = header.DataContentType switch
{
    DataContentType.DOUBLE => (object)BitConverter.ToDouble(currentValueBytes.ToArray()),
    DataContentType.FLOAT => (object)BitConverter.ToSingle(currentValueBytes.ToArray()),
    DataContentType.BYTE => (object)contentData[i],
    DataContentType.SHORT => (object)BitConverter.ToInt16(currentValueBytes.ToArray()),
    DataContentType.INTEGER => (object)BitConverter.ToInt32(currentValueBytes.ToArray()),
    DataContentType.LONG => (object)BitConverter.ToInt64(currentValueBytes.ToArray()),
    _ => throw new InvalidDataException("Invalid data type"),
};

我很想知道此时您将如何使用 value。拆箱是一项精细的操作。我唯一一次做过这样的事情是在 JSON 化操作的上游(Newtonsoft JSON 包如果很高兴序列化盒装 native 值类型)。

关于c# - 为什么这个 switch case 返回一个 double,即使它是一个 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65927527/

相关文章:

.net-core - 指定的 deps.json[] 不存在 - Blazor WebAssembly App 项目类型

c# - 无法解析参数 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider apiDescriptionsProvider

javascript - JS : Why don't the switch statement cases `case 2` and `case day == 2` print out the same result?

c++ - 使用 case switch 语句加载函数

c# - 错误: Type or namespace not found

c# - 在 C# 中仅打开一次 Windows 窗体

.net-core - 显示一对多数据模型的 ICollection 时 foreach 循环出错

java - java中生成随机数的switch语句: not working

c# - 如何在子类方法中显示父类成员的正确值

c# - 用另一个元素包装一个 HTML 元素?