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

前端 未结 7 1154
囚心锁ツ
囚心锁ツ 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 07:56

    According to the MSDN documentation, the overload of Console.WriteLine that takes an object internally calls ToString on its argument.

    When you do foreach (var value in ...), your value variable is typed as object (since, as SLaks points out, Enum.GetValues returns an untyped Array) and so your Console.WriteLine is calling object.ToString which is overriden by System.Enum.ToString. And this method returns the name of the enum.

    When you do foreach (int value in ...), you're casting the enum values to int values (instead of object); so Console.WriteLine is calling System.Int32.ToString.

提交回复
热议问题