为什么Enum.Parse()返回对象? [英] Why does Enum.Parse() return object?

查看:81
本文介绍了为什么Enum.Parse()返回对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有很多关于将字符串转换为枚举值的问题。一般来说,答案看起来像这个问题的答案:

  StatusEnum MyStatus =(StatusEnum)Enum.Parse(typeof(StatusEnum),Active,true); 

虽然这是一个完全合理的答案,您可以编写一个简化呼叫的方法, t回答为什么 Enum.Parse()返回一个对象而不是适当的枚举值的问题。为什么我必须将其转换为 StatusEnum






编辑:



基本上,问题是为什么这样的函数不是Enum类的一部分?

  public static T Parse< T>(string value)其中T:struct 
{
return(T)Enum.Parse(typeof ),值);
}

此功能完美无缺,完全符合您的期望。 StatusEnum e = Enum.Parse< StatusEnum>(Active);

解决方案

这样做是因为




    <因此, Object 是唯一可以为任何类型的枚举



    通过返回对象,API至少可以运行,即使需要转换。


    There's lots of questions on here about converting strings to an enum value. Generally, the answer looks something like the answers on this question:

    StatusEnum MyStatus = (StatusEnum) Enum.Parse( typeof(StatusEnum), "Active", true );
    

    While that's a perfectly reasonable answer, and you can write a method to simplify the call, it doesn't answer the question of why Enum.Parse() returns an object instead of the appropriate enum value. Why do I have to cast it to StatusEnum?


    Edit:

    Basically, the question is why is a function like this not part of the Enum class?

        public static T Parse<T>(string value) where T: struct 
        {
            return (T)Enum.Parse(typeof (T), value);
        }
    

    This function works perfectly fine, does exactly what you'd expect. StatusEnum e = Enum.Parse<StatusEnum>("Active");.

    解决方案

    It does this because

    1. It predated generics and (even if it hadn't:)
    2. Generic constraints can't be enums (in the mainstream .NET languages)

    As such, Object is the only type that will always work for any type of enum.

    By returning object, the API is at least functional, even if a cast is required.

    这篇关于为什么Enum.Parse()返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆