如果有人想知道:我需要为 WPF 构建一个可绑定的枚举转换器。
由于我不知道反射中的值意味着什么,我需要手动切换值(将它们绑定到复选框 pe)
将标记枚举的值设置为 -1 以设置所有位时出现问题。
如果将其设置为 -1 并且取消标记所有值,则不会导致 0,因为所有未使用的位都未取消标记。
这是最适合我的情况的方法。
SomeRightEnum someRightEnum = SomeRightEnum.CanDoNothing;
Type enumType = someRightEnum.GetType();
int newValue = 0;
var enumValues = Enum.GetValues(enumType).Cast<int>().Where(e => e == 1 || e % 2 == 0);
foreach (var value in enumValues)
{
newValue |= value;
}
Console.WriteLine(newValue);
或者,如果您想要一个扩展方法:
public static class FlagExtensions
{
public static TEnum AllFlags<TEnum>(this TEnum @enum)
where TEnum : struct
{
Type enumType = typeof(TEnum);
long newValue = 0;
var enumValues = Enum.GetValues(enumType);
foreach (var value in enumValues)
{
long v = (long)Convert.ChangeType(value, TypeCode.Int64);
if(v == 1 || v % 2 == 0)
{
newValue |= v;
}
}
return (TEnum)Enum.ToObject(enumType , newValue);
}
}