.NET 7.0是否内置了实现标志枚举按位或的方法?
.NET 7.0 是否内置了标志枚举按位或聚合的方法?
是的,.NET 7.0 可以通过LINQ的Aggregate方法直接实现你自定义OrFlags的功能,无需手动编写循环累加逻辑。
核心实现思路
Aggregate方法支持对序列执行累加操作,针对标志枚举的按位或需求,只需将累加逻辑指定为按位或运算符|即可,其行为与你自定义的OrFlags完全一致:取序列第一个元素作为初始值,依次与后续每个元素执行按位或操作,最终返回合并后的枚举值。
修改后的完整代码
[Flags] enum Props { Good, Male, Big } record Dog(string Name, Props Prop); public static async Task Main() { var list = new List<Dog>(); list.Add(new Dog("Max", Props.Male)); list.Add(new Dog("Max", Props.Big)); list.Add(new Dog("Jane", Props.Good)); var res = from d in list group d.Prop by d.Name into g select new { Name = g.Key, Properties = g.Aggregate((acc, val) => acc | val) }; foreach(var d in res) { Debug.WriteLine($"{d.Name}: {d.Properties}"); } }
输出结果
Max: Male, Big Jane: Good
额外说明
如果需要处理空序列的场景(避免抛出InvalidOperationException),可以为Aggregate指定一个种子值(建议在枚举中定义None = 0),示例如下:
[Flags] enum Props { None = 0, Good, Male, Big } // 聚合时使用种子值 Properties = g.Aggregate(Props.None, (acc, val) => acc | val)
内容的提问来源于stack exchange,提问作者Damn Vegetables
相关产品推荐
相关产品推荐

