繁体   English   中英

限制标志的可能组合

[英]restrict possible combination of Flags

有没有一种方法可以组合枚举中的标志,但可以限制可能的组合? 我有一个这样的枚举:

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

现在,我还想介绍一个FieldsOnly但要确保仅当不存在PropertiesOnly时才使用它。 这可能吗?

不,不可能。 甚至不可能将值限制为列出的项目。 例如,在C#中允许以下内容:

CopyFlags flags = (CopyFlags)358643;

您需要在包含CopyFlags参数的方法中显式执行验证。

不,在枚举的上下文中是不可能的; 相反,您必须对其进行验证:

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