问题描述
有时,当读取他人的C#代码时,我会看到一个方法可以在一个参数中接受多个枚举值。我一直认为这是一个整洁的,但从来没有看过。
Sometimes when reading others' C# code I see a method that will accept multiple enum values in a single parameter. I always thought it was kind of neat, but never looked into it.
嗯,现在我想我可能需要它,但不知道如何
Well, now I think I may have a need for it, but don't know how to
- 设置方法签名以接受此
- 使用方法中的值
-
- 定义枚举
以实现这种事情。
在我的特殊情况下,我想使用System.DayOfWeek,它定义为:
to achieve this sort of thing.
In my particular situation, I would like to use the System.DayOfWeek, which is defined as:
[Serializable]
[ComVisible(true)]
public enum DayOfWeek
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6
}
我希望能够将一个或多个DayOfWeek值传递给我的方法。我可以使用这个特殊的枚举吗?如何做上面列出的3件事情?
I want to be able to pass one or more of the DayOfWeek values to my method. Will I be able to use this particular enum as it is? How do I do the 3 things listed above?
推荐答案
定义枚举时,只需将其设置为[Flags],设置值为2的权力,它将以这种方式工作。
When you define the enum, just attribute it with [Flags], set values to powers of two, and it will work this way.
除了将多个值传递给函数之外,没有其他更改。
Nothing else changes, other than passing multiple values into a function.
例如:
[Flags]
enum DaysOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
public void RunOnDays(DaysOfWeek days)
{
bool isTuesdaySet = (days & DaysOfWeek.Tuesday) == DaysOfWeek.Tuesday;
if (isTuesdaySet)
//...
// Do your work here..
}
public void CallMethodWithTuesdayAndThursday()
{
this.RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
}
有关详细信息,请参阅。
For more details, see MSDN's documentation on Enumeration Types.
编辑响应添加的问题。
你将无法使用该枚举,除非你想做一些像pass它作为一个数组/ collection / params数组。这将让您传递多个值。标志语法需要将枚举指定为标志(或以不设计的方式来混合语言)。
You won't be able to use that enum as is, unless you wanted to do something like pass it as an array/collection/params array. That would let you pass multiple values. The flags syntax requires the Enum to be specified as flags (or to bastardize the language in a way that's its not designed).
这篇关于如何在C#中传递多个枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!