简体   繁体   中英

Grabbing the right name from an Enum in C# using a value

I have the following enumerator.

public enum Fruits
    {
        Banana = 1,
        Apple = 2,
        Blueberry = 3,
        Orange = 4
    }

And what I'd like to do is something like the following

static void FruitType(int Type)
    {
        string MyType = Enum.GetName(Fruits, Type);
    }

Basically I want the string MyType to populate with the name corresponding to the integer I input. So if I enter 1, MyType should have a value of Banana.

Eg. FruitType(1) --> MyType = Banana

The first parameter of GetName requires the type.

static void FruitType(int Type)
{
   string MyType = Enum.GetName(typeof(Fruits), Type);
}

If you're not planning on doing anything else in the method, you can return the string like this

static string FruitType(int Type)
{
   return Enum.GetName(typeof(Fruits), Type);
}

string fruit = FruitType(100);
if(!String.IsNullOrEmpty(fruit))
   Console.WriteLine(fruit); 
else
   Console.WriteLine("Fruit doesn't exist");

Basically I want the string MyType to populate with the name corresponding to the integer I input.

string str = ((Fruits)1).ToString();

You can modify your method like:

static string FruitType(int Type)
{
    if (Enum.IsDefined(typeof(Fruits), Type))
    {

        return ((Fruits)Type).ToString();
    }
    else
    {
        return "Not defined"; 
    }
}

The use it like

string str = FruitType(2);

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