为什么使用“var”时Enum.GetValues()返回名称? [英] Why does Enum.GetValues() return names when using "var"?
问题描述
任何人都可以解释这一点吗?
Can anyone explain this?
alt text http: /www.deviantsart.com/upload/g4knqc.png
using System;
namespace TestEnum2342394834
{
class Program
{
static void Main(string[] args)
{
//with "var"
foreach (var value in Enum.GetValues(typeof(ReportStatus)))
{
Console.WriteLine(value);
}
//with "int"
foreach (int value in Enum.GetValues(typeof(ReportStatus)))
{
Console.WriteLine(value);
}
}
}
public enum ReportStatus
{
Assigned = 1,
Analyzed = 2,
Written = 3,
Reviewed = 4,
Finished = 5
}
}
推荐答案
Enum.GetValues
被声明为返回
。
它返回的数组包含实际值为 ReportStatus
值。
因此, var
关键字变为对象
, / code>变量保存(boxed)键入的枚举值。
Console.WriteLine
调用解析为需要对象
并调用对象上的 ToString()
,枚举枚举返回名称。
Therefore, the var
keyword becomes object
, and the value
variable holds (boxed) typed enum values.
The Console.WriteLine
call resolves to the overload that takes an object
and calls ToString()
on the object, which, for enums, returns the name.
当您迭代 int
时,编译器会将值转换为 int
, 值
变量保持正常(和非盒装) int
值。
因此, Console.WriteLine
调用解析到需要 int
并重新打印的重载。
When you iterate over an int
, the compiler implicitly casts the values to int
, and the value
variable holds normal (and non-boxed) int
values.
Therefore, the Console.WriteLine
call resolves to the overload that takes an int
and prints it.
如果更改 int
to DateTime
(或任何其他类型),它仍然会编译,但它会抛出一个 InvalidCastException
在运行时。
If you change int
to DateTime
(or any other type), it will still compile, but it will throw an InvalidCastException
at runtime.
这篇关于为什么使用“var”时Enum.GetValues()返回名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!