如何在 C# 中将字符串转换为 Flags 枚举格式

How to convert from a string to a Flags enum format in C#

我有这个枚举:

[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;

其实我意识到这比我想象的要容易。 我需要做的就是将该字符串转换为 int,在我的例子中,或一般的 long,并将其转换为 Countries。 它将将该数字转换为预期的格式。 换句话说:

(Countries) 25 = Countries.Usa | Countries.Brazil | Countries.Chile;

使用Enum.Parse.

例如Countries c = (Countries)Enum.Parse(typeof(Countries), "Usa, Brazil...");

假设您的国家/地区字符串用逗号分隔,这似乎对我有用:

private static Countries ConvertToCountryEnum(string country)
        {
            return country.Split(',').Aggregate(Countries.None, (seed, c) => (Countries)Enum.Parse(typeof(Countries), c, true) | seed);
        }