本文介绍了Enum.HasFlag,为什么没有Enum.SetFlag?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建立一个扩展方法,每个标志I型声明,像这样:

I have to build an extension method for each flag type I declare, like so:

public static EventMessageScope SetFlag(this EventMessageScope flags, 
    EventMessageScope flag, bool value)
{
    if (value)
        flags |= flag;
    else
        flags &= ~flag;

    return flags;
}



为什么没有一个 Enum.SetFlag 好像有一个 Enum.HasFlag

此外,为什么这并不总是工作?

Also, why does this not work always?

public static bool Get(this EventMessageScope flags, EventMessageScope flag)
{
    return ((flags & flag) != 0);
}

例如,如果我有:

var flag = EventMessageScope.Private;

和检查,如:

if(flag.Get(EventMessageScope.Public))

其中 EventMessageScope.Public 真的是 EventMessageScope.Private | EventMessageScope.PublicOnly ,它返回true。

Where EventMessageScope.Public really is EventMessageScope.Private | EventMessageScope.PublicOnly, it returns true.

当它不是,因为私人不公开的,它只是半公开的。

When it's not, because Private is not public, it's just half public.

这同样适用于:

如果(flag.Get(EventMessageScope.None))

它返回,除了范围实际上是为0x0 ),当它应该总是返回true?

Which returns false, except the scope is actually None (0x0), when it should always return true?

推荐答案

&安培; 运营商将让你与 A和相同的答案; b ,因为它会随着 B和;一个,所以

The & operator will give you the same answer with a & b as it will with b & a, so

(EventMessaageScope.Private)获得(EventMessageScope.Private | EventMessageScope.PublicOnly )

是一样的写

(EventMessageScope.Private | EventMessageScope.PublicOnly)获得(EventMessaageScope.Private)

如果你只是想知道,如果值是的相同的作为EventMessaageScope.Public,那么就使用的等于的:

If you just want to know if the value is the same as EventMessaageScope.Public, then just use equals:

EventMessageScope.Private == EventMessageScope.Public

您会方法总是返回(EventMessageScope.None)获得(EventMessaageScope.None),因为无== 0 ,它只有当与操作结果的不可以零返回true。 0安培; 0 == 0

Your method will always return false for (EventMessageScope.None).Get(EventMessaageScope.None) because None == 0 and it only returns true when the result of the AND operation is not zero. 0 & 0 == 0.

这篇关于Enum.HasFlag,为什么没有Enum.SetFlag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 04:32