3

私はこの列挙型を持っています:

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

3 に答える 3

6

Enum.Parseを使用します。

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

于 2016-10-29T11:29:20.180 に答える
2

国文字列がコンマで区切られていると仮定すると、これはうまくいくようです:

private static Countries ConvertToCountryEnum(string country)
        {
            return country.Split(',').Aggregate(Countries.None, (seed, c) => (Countries)Enum.Parse(typeof(Countries), c, true) | seed);
        }
于 2016-10-29T11:42:51.150 に答える
0

Actually I realized that it is easier than what i thought. All I need to do is convert that string into an int, in my case, or a long in general, and cast it to Countries. It will convert that number into the expected format. In other words:

(Countries) 25 = Countries.Usa | Countries.Brazil | Countries.Chile;
于 2016-10-29T11:23:30.933 に答える