本文介绍了用于检测(通过反射)Enum是否为“标志"类型的策略.在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Reflection读取程序集中的类型(以生成代码).我可以看到应该使用 [Flags] 属性标记一些枚举,但是写这些枚举的人忘记了添加此属性.

I'm using Reflection to read types inside an assembly (to generate code). I can see that some enumerations should have been marked with the [Flags] attribute but whoever wrote those enums forgot to add this attribute.

是否有任何可靠的方法来检测何时可以将枚举视为标记"枚举?

Is there any reliable way of detecting when an enum can be considered a "Flags" enum?

目前,我的策略是按降序读取枚举,并检查element(last -1)* 2 == element(last)的值.

My strategy at the moment is to read the enum in descending order, and checking if the value of element(last -1) * 2 == element(last).

在大多数情况下,这很好用,除非我的枚举具有0、1和2值(可以是标志也可以不是标志).

That works great in most cases, except when I have enums with 0, 1, and 2 values (which could be flags or not).

我想将其检测为标志的枚举示例:

Example of an enum that I'd like to detect as being flags:

public enum EnumIsFlag1
{
    ItemA = 2,
    ItemB = 4,
    ItemC = ItemA + ItemB,
    ItemD = 32,
    ItemE = 64,
}


我的问题不是重复的...主持人显然没有阅读我的问题

推荐答案

很显然,只能通过启发式方法解决此问题,但我知道这就是您要解决的问题.

Clearly, this problem can only be solved heuristically but I understand that's what you are after.

通常,标志枚举将大多数成员设置为单个位.因此,我将计算仅设置一个位(例如,是2的幂)的成员的数量.

Typically, flags enums have most members with a single bit set. So I would count the number of members that have only a single bit set (e.g. that are a power of two).

然后,您可以设计一个启发式方法,例如:

Then, you can devise a heuristic such as:

//Is this a flags enum?

var totalCount = ...;
var powerOfTwoCount = ...;

if (totalCount < 3) return false; //Can't decide.
if (powerOfTwoCount >= totalCount * 0.95) return true; //Looks like flags
//Probably need some cases for small values of totalCount.

可以在合法标志枚举中设置多个位的唯一原因是标志的组合.但是,此类枚举项的数量通常很少.

The only reason multiple bits could be set in a legitimate flags enum is combinations of flags. But the number of such enum items is usually small.

这篇关于用于检测(通过反射)Enum是否为“标志"类型的策略.在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 07:31