在C#中,枚举参数是否可以是可选的?

9
我已经参考这篇有用的文章了解如何将Enum值列表作为参数传递。
现在我想知道是否可以将此参数设置为可选?
示例:
   public enum EnumColors
    {
        [Flags]
        Red = 1,
        Green = 2,
        Blue = 4,
        Black = 8
    }

我希望能够像这样调用接收枚举参数的函数:
DoSomethingWithColors(EnumColors.Red | EnumColors.Blue)

或者

DoSomethingWithColors()

我的函数应该长成什么样子?
public void DoSomethingWithColors(EnumColors someColors = ??)
 {
  ...
  }

3
顺便提一句,几乎每个“枚举”都应该为“0”定义某些值,通常对于“Flags”,它应被称为“None”。 - Damien_The_Unbeliever
3
[Flags] 属性应该放在枚举类型上,而不是枚举字段上。 - Sam Axe
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Jeppe Stig Nielsen
4个回答

13

是的,它可以选择性地使用。

[Flags]
public enum Flags
{
    F1 = 1,
    F2 = 2
}

public  void Func(Flags f = (Flags.F1 | Flags.F2)) {
    // body
}

如果不传递参数调用函数,则默认传递(Flags.F1 | Flags.F2)f参数。您可以带或不带参数地调用该函数。

如果您不想有默认值,但参数仍然是可选的,你可以这样做:

public  void Func(Flags? f = null) {
    if (f.HasValue) {

    }
}

谢谢 - 所有的评论都很有价值。可惜只能接受一个,通常第一个会被采纳。 - Cameron Castillo

6

Enum是一个值类型,因此您可以使用可空值类型EnumColors?...

void DoSomethingWithColors(EnumColors? colors = null)
{
    if (colors != null) { Console.WriteLine(colors.Value); }
}

然后将EnumColors?的默认值设置为null

另一个解决方案是将EnumColors设置为未使用的值...

void DoSomethingWithColors(EnumColors colors = (EnumColors)int.MinValue)
{
    if (colors != (EnumColors)int.MinValue) { Console.WriteLine(colors); }
}

3
以下代码是完全有效的:
void colorfunc(EnumColors color = (EnumColors.Red | EnumColors.Blue))
{
    //whatever        
}

调用它可以像这样完成:

colorfunc();
colorfunc(EnumColors.Blue);

0
你可以重载函数,因此编写两个函数:

void DoSomethingWithColors(EnumColors colors)
{
    //DoWork
}

void DoSomethingWithColors()
{
    //Do another Work, or call DoSomethingWithColors(DefaultEnum)
}

你收到了来自2009年的电话,他们要求告诉你有什么事情。 - zerkms
自2010年C#版本4以来,C#具有可选参数 - Jeppe Stig Nielsen
第一:我使用VS2008,VB.Net有可选参数,而C#没有,这就是为什么我这样认为的。所以我更新了我的答案。 第二:我的方法更清晰(对我来说),并且与之前的版本兼容。 - ZwoRmi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接