简体   繁体   English

限制标志的可能组合

[英]restrict possible combination of Flags

is there a way to combine flags within an Enum but to restrict the possible combinations? 有没有一种方法可以组合枚举中的标志,但可以限制可能的组合? I have an enum like this: 我有一个这样的枚举:

[Flags]
public enum CopyFlags
{
    /// <summary>
    /// Copy members regardless of their actual case
    /// </summary>
    CaseSensitive = 1,
    /// <summary>
    /// Indicates if a leading underscore (e.g. _myMember) should be ignored while comparing member-names.
    /// </summary>
    IgnoreLeadingUnderscore = 2,
    /// <summary>
    /// Indicates if only properties should be copied. Usefull when all technical data is stored in properties. 
    /// </summary>
    PropertiesOnly = 4
}

Now I want to also introduce a FieldsOnly -value but ensure that it is only used when PropertiesOnly is not present. 现在,我还想介绍一个FieldsOnly但要确保仅当不存在PropertiesOnly时才使用它。 Is this possible? 这可能吗?

No, it is not possible. 不,不可能。 It's not even possible to restrict the values to being the items listed. 甚至不可能将值限制为列出的项目。 For example, the following is allowed in C#: 例如,在C#中允许以下内容:

CopyFlags flags = (CopyFlags)358643;

You need to perform your validation explicitly inside of the methods which include a CopyFlags parameter. 您需要在包含CopyFlags参数的方法中显式执行验证。

No, it's not possible within the context of the enum; 不,在枚举的上下文中是不可能的; instead, you'd have to validate it: 相反,您必须对其进行验证:

public void DoSomething(CopyFlag flag)
{
   if (flag.HasFlag(CopyFlags.PropertiesOnly) && flag.HasFlag(CopyFlags.FieldsOnly))
      throw new ArgumentException();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM