为什么使用"什么时候Enum.GetValues()的返回名称; VAR"? [英] Why does Enum.GetValues() return names when using "var"?
问题描述
有人能解释一下吗?
使用系统;
命名空间TestEnum2342394834
{
类节目
{
静态无效的主要(字串[] args)
{
//以VAR
的foreach(VAR值Enum.GetValues(typeof运算(ReportStatus)))
{
Console.WriteLine(值);
}
//与INT
的foreach(在Enum.GetValues(typeof运算(ReportStatus)int值))
{
Console.WriteLine (值);
}
}
}
公共枚举ReportStatus
{
分配= 1,
分析= 2 ,
写= 3,
发表= 4,
说完= 5
}
}
Enum.GetValues
声明为返回阵列
。结果
,它返回数组包含实际值 ReportStatus
值。
因此, VAR
关键字变对象
和值
变量保存(盒装)类型的枚举值。结果
中的 Console.WriteLine
调用解析为接受一个<$ C超载$ C>对象键,通话的ToString()
上的对象,其中,用于枚举,返回名称。
当您遍历一个 INT
,编译器隐式注塑值 INT
,和在值
变量保存正常(和非盒装) INT
值。结果
因此, Console.WriteLine
调用解析为发生过载的 INT
并打印。
如果您更改 INT
到的DateTime
(或任何其他类型),它仍然会编译,但它会抛出一个 InvalidCastException的
在运行时。
Can anyone explain this?
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
is declared as returning Array
.
The array that it returns contains the actual values as ReportStatus
values.
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.
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.
If you change int
to DateTime
(or any other type), it will still compile, but it will throw an InvalidCastException
at runtime.
这篇关于为什么使用"什么时候Enum.GetValues()的返回名称; VAR"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!