C# 发现使用 var 关键字声明的变量的隐式类型

C# Discover Implicit Type of variable declared with the var keyword

假设我有以下代码:

var longValue = 2147483650; // Three more than the max int size
var intValue = 10;
var variableOfUnknownType = longValue - intValue;

我想知道 variableOfUnkownType 是什么类型。 (即 variableOfUnknownType.GetType() == System.Int64 还是 variableOfUnkownType.GetType() == System.Int32?)

当然,我可以去仔细阅读有关算术类型转换的 C# 文档,或者在我的代码中添加 Console.WriteLine(variableOfUnknownType.GetType()); 语句来了解这个问题的答案。但是,根据 C#'s var documentation

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

这意味着 MS Visual Studio 应该能够在编译代码之前告诉我变量的类型。

我的问题是: 我如何使用 MS Visual Studio 告诉我这个特定 var 变量的值?

只需将鼠标悬停在 'var' 关键字上,它会告诉您推断的类型

tl;博士;回答 将鼠标悬停在 "var" 上,您会看到类型(提示它是 Int64/long)

长答案: 只需将您的代码替换为 var 代表的类型,您就会得到以下代码:

uint longValue = 2147483650; // Three more than the max int size
int intValue = 10;
long variableOfUnknownType = longValue - intValue;

如您所见,这是三种不同的类型,但为什么呢?单位是有道理的。没有必要占用 64 位,如果你可以用 32 位做同样的事情,因为这是一个正数,我们可以使用一个无符号整数。 int 是不言自明的,但是 long 起初有点令人困惑。

作为程序员,我们知道 int.MaxValue + 3 - 10 又适合 int,但编译器并不知道。毕竟,他怎么知道 intVariable 是 10?简单:他没有。因此,他推断出他知道可以处理该值的类型。由于我们这里是做减法,可能会出现负值,所以他取的是有符号类型,可以拟合值,也就是Int64/long

顺便说一句:这超出了我的想象。我必须再次检查 c# 中的整数运算才能完全验证这一点。