sách gpt4 ăn đã đi

c# - 如何获得枚举的所有可能组合(标志)

In lại 作者:太空狗 更新时间:2023-10-29 22:28:25 26 4
mua khóa gpt4 giày nike

[Flags]
public enum MyEnum
{
None = 0,
Setting1 = (1 << 1),
Setting2 = (1 << 2),
Setting3 = (1 << 3),
Setting4 = (1 << 4),
}

我需要能够以某种方式遍历每个可能的设置并将设置组合传递给一个函数。可悲的是,我一直无法弄清楚如何做到这一点

câu trả lời hay nhất

未经测试,使用风险自负,但应该足够普遍地解决问题。 System.Enum 不是一个有效的限制,因为从技术上讲,C# 只允许在 lớp học 中继承/与 lớp học 后端绕过 EnumValueType 。很抱歉丑陋的类型转换。它的效率也不是很高,但除非您针对动态生成的类型运行它,否则每次执行只需要执行一次(如果保存的话,则执行一次)。

public static List GetAllEnums()
where T : struct
// With C# 7.3 where T : Enum works
{
// Unneeded if you add T : Enum
if (typeof(T).BaseType != typeof(Enum)) throw new ArgumentException("T must be an Enum type");

// The return type of Enum.GetValues is Array but it is effectively int[] per docs
// This bit converts to int[]
var values = Enum.GetValues(typeof(T)).Cast().ToArray();

if (!typeof(T).GetCustomAttributes(typeof(FlagsAttribute), false).Any())
{
// We don't have flags so just return the result of GetValues
return values;
}

var valuesInverted = values.Select(v => ~v).ToArray();
int max = 0;
for (int i = 0; i < values.Length; i++)
{
max |= values[i];
}

var result = new List();
for (int i = 0; i <= max; i++)
{
int unaccountedBits = i;
for (int j = 0; j < valuesInverted.Length; j++)
{
// This step removes each flag that is set in one of the Enums thus ensuring that an Enum with missing bits won't be passed an int that has those bits set
unaccountedBits &= valuesInverted[j];
if (unaccountedBits == 0)
{
result.Add((T)(object)i);
phá vỡ;
}
}
}

//Check for zero
thử
{
if (string.IsNullOrEmpty(Enum.GetName(typeof(T), (T)(object)0)))
{
result.Remove((T)(object)0);
}
}
nắm lấy
{
result.Remove((T)(object)0);
}

trả về kết quả;
}

这是通过获取所有值并将它们组合在一起而不是求和来实现的,以防包含合数。然后它将每个整数取到最大值并用每个 Flag 的反转来屏蔽它们,这导致有效位变为 0,使我们能够识别那些不可能的位。

最后的检查是从枚举中丢失零。如果您愿意始终在结果中包含零枚举,则可以将其删除。

给定包含 2,4,6,32,34,16384 的枚举时,给出预期结果 15。

关于c# - 如何获得枚举的所有可能组合(标志),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6117011/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress