Why does Enum.GetValues() return names when using “var”?

前端 未结 7 1057
囚心锁ツ
囚心锁ツ 2021-01-17 07:44

Can anyone explain this?

alt text http://www.deviantsart.com/upload/g4knqc.png

using System;

namespace TestEnum2342394834
{
    class Program
    {
         


        
7条回答
  •  爱一瞬间的悲伤
    2021-01-17 08:00

    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.

提交回复
热议问题