![](/img/trans.png)
[英]Switch on Enum (with Flags attribute) without declaring every possible combination?
[英]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.