gpt4 book ai didi

c# - 带文字数字的条件运算符返回类型

转载 作者:太空狗 更新时间:2023-10-30 01:20:38 24 4
gpt4 key购买 nike

?: Operator (C# Reference)

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

Integer literals

If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.

考虑:

var value = test ? (Int64)1 : 0;

0,一个没有后缀的十进制数字字面量将被转换成一个intint 可以隐式转换为 Int64。由于这种转换只发生在一个方向,我们可以放心,返回值将是一个 Int64。

但是:

var value = test ? (UInt64)1 : 0;

UInt64int 不能相互隐式转换,但是这段代码编译运行,结果类型是 UInt64

什么时候确定0的类型?

如果这两种类型可以相互隐式转换,那么您最终会选择这两种类型中的哪一种? (我不认为这通常会发生,但用户生成的类可以实现这种转换。)

前期研究:
我发现了其他几个标题相似的问题,但它们都与 null 或 nullable 类型有关。

相关性:这在我的代码中很重要,因为我们立即将此结果传递给 ByteWriter.Write,并希望以写入正确字节数的正确重载结束。这些示例当然已大大简化。

替代语法使结果显式可能是清晰的最佳选择,无论在没有显式转换的情况下实际发生了什么:

var value = test ? (UInt64)1 : (UInt64)0;

最佳答案

请注意,当数字是编译时常量(文字)时,存在一组整数类型之间的隐式转换,而当它们不是常量时,存在另一组转换。

您的有趣示例是:

var value = test ? (UInt64)1 : 0;

也可以这样写:

var value = test ? 1ul : 0;

其中ul后缀表示ulong,即System.UInt64

当使用文字(常量)时,确实存在从 int (System.Int32) 到 ulong 的隐式转换,但仅当int 常量是非负的。它真的是一样的:

const ulong a = 1ul;
const int b = 0;
var value = test ? a : b; // also works fine

正如我所说,它之所以有效,是因为从 int(因为编译器知道 b 不是负数)到 ulong 的隐式常量转换>.

现在,去掉 const 得到:

ulong a = 1ul;
int b = 0;
var value = test ? a : b; // compile-time error, no implicit conversion in either direction!

我们看到对于非常量,不存在任何方向的隐式转换,因此 ab 没有最佳通用类型,这失败了。

关于c# - 带文字数字的条件运算符返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18497447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com