English 中文(简体)
使用国旗的利弊如何?
原标题:What are the pros and cons of using a flags enum?

I m receiving several bit fields from hardware.

My code was originally:

public readonly byte LowByte;

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

然后,我记得国旗,正在考虑将其改为:

[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; } }

等等。

哪些是最佳做法,哪些是每一种做法的利弊?

EDIT:我很想知道两种办法之间是否有任何实际差异,特别是在业绩方面。 我不想征求关于编码风格的意见(除非从微软准则中得出),因为这会使问题变得不建设性。 感谢。

最佳回答

至少,你的第二个例子有较好的调子,并表明该守则中各条轨道的含义。 守则中有一些关于使用该比值的文件。

否则,根据你的第一个例子,你将需要补充评论,因为你基本上是 t(比)的人物,这使《守则》更难阅读,特别是没有熟悉的其他人。 即便你本人在路上将连续六个月维持这一法典,你也可能会发现难以记住第5条的内容。

问题回答

嗣后是最佳做法,因为它使你的法典更加可读。

如果你使用4.0.NET,你现在可以使用<代码>HasFlag方法,检查一个信标是否包含一个特定轨道。 这使得它比以往的检查方法更容易阅读。

[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.HasFlag(LowByte.Timer));
  } 
}

http://msdn.microsoft.com/en-us/library/system.enum.hasflag.aspx” rel=“nofollow”>MSDN





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签