什么是使用标志枚举的利弊? [英] What are the pros and cons of using a flags enum?

查看:138
本文介绍了什么是使用标志枚举的利弊?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到来自硬件几个位字段

I'm receiving several bit fields from hardware.

我的代码最初是:

public readonly byte LowByte;

public bool Timer { get { return (LowByte & 1) == 1; } }



然后我想起这些标志枚举,并正在考虑将其更改为:

Then I remembered the flags enum and am considering changing it to:

[Flags]
public enum LowByteReasonValues : byte
{
    Timer = 1,
    DistanceTravelledExceeded = 2,
    Polled = 4,
    GeofenceEvent = 8,
    PanicSwitchActivated = 16,
    ExternalInputEvent = 32,
    JourneyStart = 64,
    JourneyStop = 128
}

public readonly LowByteReasonValues LowByte;

public bool Timer { get { return (LowByte & LowByteReasonValues.Timer) == LowByteReasonValues.Timer; } }



等等。

and so on.

这是最好的做法,如果有任何每种方法的利弊

Which is best practice and what if any are the pros and cons of each approach?

编辑:我想知道是否有两种方法之间的实际差别,特别是关于性能。我不希望征求对编码风格的意见(除非它来自微软的准则)为将看到的问题作为封闭建设性。谢谢你。

I'm interested to know if there are any practical differences between the two approaches, particularly in regards to performance. I'm not wishing to solicit opinion on coding styles (unless it comes from Microsoft guidelines) as that would see the question closed as unconstructive. Thanks.

推荐答案

最起码,你的第二个例子中具有更好的语义和表示代码中的位的含义。有什么样的位用于代码中的一些文档。

At the very least, your second example has better semantics and indicates the meaning of the bits within the code. There is some documentation within the code of what the bit is used for.

另外,根据您的第一个例子,你将需要添加注释,因为你基本上是摆弄法宝(位)数,这使得更加难以代码阅读,特别是由另一个不熟悉它的人。即使你自己将维护该代码半年下来的路,你会发现它很难记住5用于什么位。

Otherwise, based on your first example, you will need to add comments since you are basically twiddling magic (bit) numbers, which makes the code much more difficult to read, especially by another person not familiar with it. Even if you yourself will be maintaining this code six months down the road, you may find it difficult to remember what bit 5 was used for.

这篇关于什么是使用标志枚举的利弊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆