[英]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. 基本上,我希望字符串MyType用与我输入的整数相对应的名称填充。 So if I enter 1, MyType should have a value of Banana.
因此,如果输入1,则MyType的值应为Banana。
Eg. 例如。 FruitType(1) --> MyType = Banana
FruitType(1)-> MyType =香蕉
The first parameter of GetName requires the type. GetName的第一个参数需要类型。
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. 基本上,我希望字符串MyType用与我输入的整数相对应的名称填充。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.