c# - 如何在 Silverlight 中创建与 .NET 中工作方式相同的 GetEnumValues 扩展方法?

标签 c# silverlight

下面是一段我觉得很有用的代码,我可以用它来快速限制枚举。 CurrentEnum 存储对用于提供字符串的枚举的引用,在本例中为“Bald”,它可以更改。

我想做的是在没有 GetEnumValues 函数的 Silverlight 中复制相同的功能。更好的解决方案是一种扩展方法,其使用方式与我在下面的示例中的方式相同。

class Program
{
    enum Cats { Fluffy, Furry, Bald };
    enum Dogs { Big, Fat, Ugly };

    static Type CurrentEnum = typeof(Cats);

    static void Main(string[] args)
    {
        Int32 i = (Int32)Enum.Parse(CurrentEnum, "Bald", true);
        i = i == CurrentEnum.GetEnumValues().Length - 1 ? 0 : i + 1;
        String nextValue = CurrentEnum.GetEnumValues().GetValue(i).ToString();

        Console.WriteLine(nextValue);
        Console.ReadKey();
    }
}

更新:

这是我现在的决定:

public static class Extensions
{
    public static Array GetEnumValues(this Type enumType)
    {
        if (enumType == null) throw new ArgumentException("Type 'enumType' cannot be null");
        if (!enumType.IsEnum) throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");

        Int32 i = 0;
        Boolean bDefined = true;
        List<String> list = new List<String>();

        do
        {
            if (Enum.IsDefined(enumType, i))
            {                    
                list.Add(Enum.GetName(enumType, i));
                ++i;
            }
            else
            {
                bDefined = false;
            }
        }
        while (bDefined);

        return list.ToArray();
    }
}

最佳答案

如果我不得不猜测(未经测试):

    public static Array GetValues(Type type)
    {
        var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
        Array result = Array.CreateInstance(type, fields.Length);
        for(int i = 0 ; i < fields.Length ; i++)
        {
            result.SetValue(Enum.ToObject(type, fields[i].GetValue(null)), i);
        }
        return result;
    }

请注意,我不打算在这里解决排序问题;字段顺序未明确定义。所以使用它来获取值没有特定的顺序

关于c# - 如何在 Silverlight 中创建与 .NET 中工作方式相同的 GetEnumValues 扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7062208/

相关文章:

c# - SqlCommand 正确关闭连接

c# - 单击时功能区按钮不触发 onAction 设置的事件

c# - HTMLAgilityPack : Screen Scraping Unable to Find a Div with Hyphen in Class Name?

c# - WPF 中的 Windows 8 选项卡控件样式

c# - View 模型类生成

silverlight - Mvvm Light和EventToCommand-文本框LostFocus触发两次

c# - Identity 2.1 - 未找到 UserId 但之前在工作

c# - 托管环境中的多线程 Pinvoked DLL。是否可以?

asp.net - asp.net、javascript 和 silverlight 的共享本地化?

silverlight - 使用MVVM Light将消息发送到Silverlight中的未构造类