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

前端 未结 7 1058
囚心锁ツ
囚心锁ツ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 08:05

    FWIW, here's the disassembled code from Enum.GetValues() (via Reflector):

    [ComVisible(true)]
    public static Array GetValues(Type enumType)
    {
        if (enumType == null)
        {
            throw new ArgumentNullException("enumType");
        }
        if (!(enumType is RuntimeType))
        {
            throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
        }
        if (!enumType.IsEnum)
        {
            throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
        }
        ulong[] values = GetHashEntry(enumType).values;
        Array array = Array.CreateInstance(enumType, values.Length);
        for (int i = 0; i < values.Length; i++)
        {
            object obj2 = ToObject(enumType, values[i]);
            array.SetValue(obj2, i);
        }
        return array;
    }
    

    Looks like what everyone's saying about the var being an object and calling object.ToString() returning the name is correct...

提交回复
热议问题