如何在 C# 中传递多个枚举值? [英] How do you pass multiple enum values in C#?
问题描述
有时在阅读其他人的 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);
}
有关详细信息,请参阅 MSDN 关于枚举类型的文档.
For more details, see MSDN's documentation on Enumeration Types.
根据问题的补充进行编辑.
Edit in response to additions to question.
您将无法按原样使用该枚举,除非您想执行诸如将其作为数组/集合/参数数组传递之类的操作.那会让你传递多个值.标志语法要求将 Enum 指定为标志(或以非其设计的方式混杂该语言).
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# 中传递多个枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!