I'm wondering if the following is possible:
The method Regex.Match
can receive an enum, so I can specify:
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).
Could I use |
operator like in C/C++?
You need to annotate it with [Flags]
attribute and use |
operator to combine them.
In the case you mentioned, you can do that because RegexOptions
enum is annotated with it.
A helpful way to use the FlagsAttribute with enumerations
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
:
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.
Don't use &
, use |
(you want to do a bit-wise Boolean OR).
Just to enhance the answers a bit, the Flags attribute is not a requirement. 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).
To test if a condition is set you normally would use a bitwise &. This will also work without the Flags attribute.
In the MSDN documentation for this attribute there is an example of two enums, one with and the other without it: FlaggsAttribute .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.