开发者

Iterate through enum in Silverlight 4 [duplicate]

开发者 https://www.devze.com 2023-02-11 10:31 出处:网络
This question already has answers here: 开发者_运维百科 Closed 11 years ago. Possible Duplicate: Iterating through an enumeration in Silverlight?
This question already has answers here: 开发者_运维百科 Closed 11 years ago.

Possible Duplicate:

Iterating through an enumeration in Silverlight?

Is there a way to iterate through all values in an Enum in Silverlight with C#?

I know WPF allows you to use the System.Enum.GetType(Type) method, but this is not available in Silverlight.

Thanks, Seth


    public static IEnumerable<T> GetEnumValues<T>()
    {
        return typeof(T)
            .GetFields()
            .Where(x => x.IsLiteral)
            .Select(field => (T)field.GetValue(null));
    }

usage

        foreach (var bindingFlag in GetEnumValues<BindingFlags>())
        {
            Debug.WriteLine(bindingFlag);
        }


Try this:

    public static List<T> GetList<T>(Type enumType)
    {
        List<T> output = new List<T>();

        var fields = from field in enumType.GetFields()
                     where field.IsLiteral
                     select field;


        foreach (FieldInfo field in fields)
        {
            object value = field.GetValue(enumType);
            output.Add((T) value);
        }

        return output;

    }

Call it like this:

List<MyEnum> myList = GetList<MyEnum>(typeof(MyEnum))
0

精彩评论

暂无评论...
验证码 换一张
取 消