gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:44:47 25 4
gpt4 key购买 nike

下面是一段我觉得很有用的代码,我可以用它来快速限制枚举。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com