简体   繁体   English

转换为枚举与Enum.ToObject

[英]Casting to enum vs. Enum.ToObject

I recently saw a project that was using this style : 我最近看到一个使用这种风格的项目:

(SomeEnum)Enum.ToObject(typeof(SomeEnum), some int)

instead of this style: 而不是这种风格:

(SomeEnum)some int

Why use the former? 为什么要使用前者? Is it just a matter of style? 这只是风格问题吗?

From MSDN: 来自MSDN:

This conversion method returns a value of type Object. 此转换方法返回Object类型的值。 You can then cast it or convert it to an object of type enumType. 然后,您可以将其转换或转换为enumType类型的对象。

https://msdn.microsoft.com/en-us/library/ksbe1e7h(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/ksbe1e7h(v=vs.110).aspx

It seems to me that MSDN tells me that I should call ToObject(), and then I can cast. 在我看来,MSDN告诉我,我应该调用ToObject(),然后我可以强制转换。 But I'm confused because I know I can cast without calling that method. 但我很困惑,因为我知道我可以在不调用该方法的情况下进行投射。 What is the purpose of ToObject()? ToObject()的目的是什么? What does it accomplish that simple casting does not? 它完成了什么简单的铸造不?

In most cases simple cast is enough. 在大多数情况下,简单演员就足够了

But sometimes you get type only in runtime. 但有时你只在运行时获得类型。 Here comes Enum.ToObject into play. 这里有Enum.ToObject进入游戏。 It can be used in cases, when you need dynamically get enum values (or maybe metadata (attributes) attached to enum values). 它可以在需要动态获取枚举值(或者可能附加到枚举值的元数据(属性))的情况下使用。 Here is an simple example: 这是一个简单的例子:

enum Color { Red = 1, Green, Blue }
enum Theme { Dark = 1, Light, NotSure }

public static void Main(string[] args)
{
    var elements = new[]
    {
        new { Value = 1, Type = typeof(Color) },
        new { Value = 2, Type = typeof(Theme) },
        new { Value = 3, Type = typeof(Color) },
        new { Value = 1, Type = typeof(Theme) },
        new { Value = 2, Type = typeof(Color) },
    };

    foreach (var element in elements)
    {
        var enumValue = Enum.ToObject(element.Type, element.Value);
        Console.WriteLine($"{element.Type.Name}({element.Value}) = {enumValue}");
    }
}

Output is: 输出是:

Color(1) = Red
Theme(2) = Light
Color(3) = Blue
Theme(1) = Dark
Color(2) = Green

More info on enum casting 关于枚举的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM