简体   繁体   中英

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

Given the 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?

您可以通过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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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