为什么Enum.Parse()返回的对象? [英] Why does Enum.Parse() return object?
问题描述
有许多关于字符串转换为一个枚举值上的问题在这里。一般情况下,答案看起来像答案在这个问题:
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 );
虽然这是一个完全合理的答案,你可以写一个方法来简化呼叫,这不是' ŧ回答问题的为什么 Enum.Parse()返回一个对象
而不是适当枚举值。为什么我必须把它转换为 StatusEnum
?
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
?
< STRONG>编辑:
基本上,问题是,为什么像枚举类的这种不属于功能
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);
}
这功能工作完全正常,正是你所期待什么呢。 StatusEnum E = Enum.Parse< StatusEnum>(激活);
。
This function works perfectly fine, does exactly what you'd expect. StatusEnum e = Enum.Parse<StatusEnum>("Active");
.
推荐答案
它这样做是因为
- 它早泛型和(即使它没有:)
- 泛型约束不能枚举(在主流的.NET语言)
因此,对象
仅仅是将始终对任何类型的枚举<工作类型/ code>
As such, Object
is the only type that will always work for any type of enum
.
通过返回对象,所述API是至少功能性的,即使需要一个铸造
By returning object, the API is at least functional, even if a cast is required.
这篇关于为什么Enum.Parse()返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!