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

标签 c# implicit-conversion conditional-operator return-type

?: 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/

相关文章:

c# - 如何注册所有类型的接口(interface)并统一获取它们的实例?

c - 为什么这个程序输出 Yes,而它应该抛出错误或 NO

c++ - C Shell(cpp.sh,基于浏览器的编译器)正在运行 Visual Studio 不会运行的程序

c++ - 与类型转换运算符一起使用时条件运算符 "?:"的编译器错误

php - 什么是 ? : in PHP 5. 3?

c# - JWT header 算法 : is "hs256" the same as "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"

c# - ModelState 错误 - Newtonsoft.Json.JsonSerializationException : Cannot populate list type System.Net.TrackingStringDictionary

c# - 如何从 BinaryExpression 获取运算符

c++ - 是什么让 enum -> int 比 enum -> unsigned 转换更好?

c++ - return 语句何时需要显式 move ?