简体   繁体   English

C# - 如何在具有属性的枚举中找到键值?

[英]C# - how do I find a key value inside an enum with a property?

Given the C# enum: 鉴于C#enum:

public enum options: byte
{
    yes = 0,
    no = 22,
    maybe = 62,
    foscho = 42
}

How do you retrieve the String 'maybe' if given the byte 62? 如果给出字节62,你如何检索字符串'maybe'?

您可以通过ToString()将其强制转换为enum和retreive:

var result = ((options)62).ToString();

var stringValue = Enum.GetName(typeof(options), 62); // returns "maybe"

Which you might also want to wrap in a check: 您可能还想在支票中包装:

if (Enum.IsDefined(typeof(options), 62))
{
    var stringValue = Enum.GetName(typeof(options), 62);    // returns "maybe"`
}

MSDN link MSDN链接

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

相关问题 (C#)如何将我的Enum转换为以VALUE作为属性,以KEY作为char(枚举的值)的字典? - (C#) How can I convert my Enum to a dictionary getting the VALUE as the attribute and the KEY as the char(value of the enum)? 如何根据 C# 中的枚举值获得优势? - How do I get an advantage depending on enum value in C#? 在C#中,如何在递归遍历ExpandoObject时更改键值属性的值? - In C#, how do I change a Key-Value-Property's value while recursively traversing an ExpandoObject? 当值为 Object 时,如何在 Unity 中使用 C# 字典通过值查找键 - How do I find key through value with C# dictionary in Unity when value is an Object 在C#中从动态获取属性时,如何检查枚举属性? - How do I check enum property when the property is obtained from dynamic in C#? 如何在另一个枚举中设置枚举值? - How do I set an enum value inside another enum? 如何在C#代码中找到属性的来源? - How do I find the origin of a property in C# code? 如何在C#中将IEnumerable <Enum>转换为Enum? - How do I convert IEnumerable<Enum> to Enum in C#? C# - 如何找到列表框项的数据库键? - C# - How do I find the database key of a Listbox item? 如何在C#中找到字符的键代码? - How do I find the key code of a character in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM