我有这个枚举:
[Flags]
public enum Countries
{
None = 0,
USA = 1,
Mexico = 2,
Canada = 4,
Brazil = 8,
Chile = 16
}
我收到如下输入字符串:
string selectedCountries = "Usa, Brazil, Chile";
如何将它(在C#中)转换回:
var myCountries = Countries.Usa | Countries.Brazil | Countries.Chile;
答案 0 :(得分:2)
使用Enum.Parse。
e.g。 Countries c = (Countries)Enum.Parse(typeof(Countries), "Usa, Brazil...");
答案 1 :(得分:1)
这似乎对我有用,假设你的国家字符串用逗号分隔:
private static Countries ConvertToCountryEnum(string country)
{
return country.Split(',').Aggregate(Countries.None, (seed, c) => (Countries)Enum.Parse(typeof(Countries), c, true) | seed);
}
答案 2 :(得分:0)
实际上我意识到它比我想象的要容易。 我需要做的就是将该字符串转换为int,在我的情况下,或者将其转换为long,并将其转换为States。 它会将该数字转换为预期的格式。 换句话说:
(Countries) 25 = Countries.Usa | Countries.Brazil | Countries.Chile;