[英]How can I pass more than one enum to a method that receives only one?
I'm wondering if the following is possible: 我想知道以下是否可行:
The method Regex.Match
can receive an enum, so I can specify: Regex.Match
方法可以接收枚举,所以我可以指定:
RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline
What if I need to specify more than just one? 如果我需要指定的不仅仅是一个,该怎么办? (eg. I want my regex to be Multiline
and I want it to ignore the pattern whitespace). (例如,我希望我的正则表达式是Multiline
,我希望它忽略模式空格)。
Could I use |
我能用|
operator like in C/C++? 像C / C ++中的运算符?
You need to annotate it with [Flags]
attribute and use |
您需要使用[Flags]
属性对其进行注释并使用|
operator to combine them. 运营商将它们结合起来
In the case you mentioned, you can do that because RegexOptions
enum is annotated with it. 在你提到的情况下,你可以这样做,因为RegexOptions
枚举用它注释。
A helpful way to use the FlagsAttribute with enumerations 将FlagsAttribute与枚举一起使用的有用方法
Definition: 定义:
[FlagsAttribute]
public enum NewsCategory : int
{
TopHeadlines =1,
Sports=2,
Business=4,
Financial=8,
World=16,
Entertainment=32,
Technical=64,
Politics=128,
Health=256,
National=512
}
Use: 使用:
mon.ContentCategories = NewsCategory.Business |
NewsCategory.Entertainment |
NewsCategory.Politics;
由于它是带有Flags属性的Enum,您可以使用:
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhiteSpace | RegexOptions.Multiline
If it is a Flags
enum you need to to a bitwise OR
: 如果它是Flags
枚举,你需要按位OR
:
var combine = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhiteSpace | RegexOptions.Multiline;
myFunction(combine);
If this is not such an enum, you are out of luck. 如果这不是这样的枚举,那你就不走运了。
See http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx for details. 有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx 。
Don't use &
, use |
不要使用&
,请使用|
(you want to do a bit-wise Boolean OR). (你想做一个按位布尔OR)。
Just to enhance the answers a bit, the Flags attribute is not a requirement. 只是为了增强答案,Flags属性不是必需的。 Every enum value can be combined with the bitwise | 每个枚举值都可以与按位组合 operator. 运营商。 The Flags attribute only makes the enum a bit more readable when converted into a string (eg. instead of seeing a number with the bitwise result as a number, you see the selected flags combined). Flags属性仅在转换为字符串时使枚举更具可读性(例如,不是看到带有按位结果的数字作为数字,您会看到所选的标志组合在一起)。
To test if a condition is set you normally would use a bitwise &. 要测试是否设置了条件,通常会使用按位&。 This will also work without the Flags attribute. 这也可以在没有Flags属性的情况下工作。
In the MSDN documentation for this attribute there is an example of two enums, one with and the other without it: FlaggsAttribute . 在此属性的MSDN文档中,有两个枚举的示例,一个用于,另一个没有它: FlaggsAttribute 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.