0

有没有办法在枚举中组合标志但限制可能的组合?我有一个这样的枚举:

[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-value 但确保它仅在PropertiesOnly不存在时使用。这可能吗?

4

2 回答 2

4

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

CopyFlags flags = (CopyFlags)358643;

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

于 2014-08-28T13:04:08.693 回答
1

不,在枚举的上下文中这是不可能的;相反,您必须验证它:

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

}
于 2014-08-28T13:05:46.337 回答