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:
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 i开发者_运维知识库t 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.
More References:
A helpful way to use the FlagsAttribute with enumerations
Example Snippet from above CodeProject article:
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;
Since it is an Enum with a Flags Attribute, you can use:
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.
精彩评论