下面是一段我觉得有用的代码,我可以用它来快速压缩枚举. CurrentEnum存储对用于提供字符串的枚举的引用,在本例中为“Bald”,它可以更改.
我想要做的是复制Silverlight中没有GetEnumValues函数的相同功能.优选的解决方案是一种扩展方法,可以使用与我下面的示例相同的方式.
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;
}
请注意,我不打算在这里解决订购问题;字段的顺序明确没有定义.因此,使用它来获取没有特定顺序的值.
原文地址:https://codeday.me/bug/20190613/1236192.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。