c# - - - 将enum用作变量()?

这个问题已经在这里有答案:


 Console.WriteLine("What time of year is it?");


 var input = Console.ReadLine();



 //earlier it was just


 //time = Year.Winter;



 switch (time)


 {


 case Year.Autumn:


 Console.WriteLine("You're gonna have to grab the leaves");


 break;



 case Year.Summer:


 Console.WriteLine("Let's go to the beach");


 break;



 case Year.Winter:


 Console.WriteLine("Better to warm up at home");


 break;


 case Year.Spring:


 Console.WriteLine("Best time of the year!");


 break;



 default:


 Console.WriteLine("I don't know this time of year");


 break;


 }



时间:

通过使用Enum类之一,可以将尝试解析为Enum


var ignoreCase = true; // decide this


if (Enum.TryParse<MyEnum>("my string", ignoreCase, out var r))


 // use r


else


 Console.WriteLine("Please enter the correct value.");




time = input.Trim().Contains("winter") ? Year.Winter: (input.Trim().Contains("summer") ?Year.Summer :(input.Trim().Contains("autumn") ?Year.Autumn:i(nput.Trim().Contains("autumn") ?Year.Autumn: null)));



...