[英]Grabbing the right name from an Enum in C# using a value
我有以下列舉者。
public enum Fruits
{
Banana = 1,
Apple = 2,
Blueberry = 3,
Orange = 4
}
我想做的是如下所示
static void FruitType(int Type)
{
string MyType = Enum.GetName(Fruits, Type);
}
基本上,我希望字符串MyType用與我輸入的整數相對應的名稱填充。 因此,如果輸入1,則MyType的值應為Banana。
例如。 FruitType(1)-> MyType =香蕉
GetName的第一個參數需要類型。
static void FruitType(int Type)
{
string MyType = Enum.GetName(typeof(Fruits), Type);
}
如果您不打算在該方法中進行任何其他操作,則可以返回這樣的字符串
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");
基本上,我希望字符串MyType用與我輸入的整數相對應的名稱填充。
string str = ((Fruits)1).ToString();
您可以像這樣修改您的方法:
static string FruitType(int Type)
{
if (Enum.IsDefined(typeof(Fruits), Type))
{
return ((Fruits)Type).ToString();
}
else
{
return "Not defined";
}
}
像這樣使用
string str = FruitType(2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.