Why does Enum.Parse() return object?

2020-08-10 08:14发布

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");.

标签: c# enums
4条回答
别忘想泡老子
2楼-- · 2020-08-10 08:19

A solution could be to use a static extension method.

public static class StringExtensions
{
    public static T ParseEnum<T>(this string t) where T: struct 
    {
        return (T)Enum.Parse(typeof (T), t);
    }
}

...

var EnumValue = "StringValue".ParseEnum<MyEnum>();
查看更多
三岁会撩人
3楼-- · 2020-08-10 08:33

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.

查看更多
狗以群分
4楼-- · 2020-08-10 08:40

TryParse does however support a type parameter:

Enum.TryParse<FooEnum>(name, true, out ret);

Therefore, if you specify the out value ret as FooEnum ret;, you won't need to cast it to a FooEnum afterwards; it'll be of the proper type right away.

查看更多
▲ chillily
5楼-- · 2020-08-10 08:41

The actual type of the object is indeed StatusEnum. The compiler, and the code, when writing Enum.Parse has no idea what that runtime object will be at the time the method is written. It won't be known until the method is actually called.

查看更多
登录 后发表回答