枚举参数在c#中是可选的吗?

Cam*_*llo 6 c# enums optional-parameters

我已经使用这篇有用的帖子来学习如何将枚举值列表作为参数传递.

现在我想知道我是否可以使这个参数可选?

例:

   public enum EnumColors
    {
        [Flags]
        Red = 1,
        Green = 2,
        Blue = 4,
        Black = 8
    }
Run Code Online (Sandbox Code Playgroud)

我想调用我的函数接收Enum param,如下所示:

DoSomethingWithColors(EnumColors.Red | EnumColors.Blue)
Run Code Online (Sandbox Code Playgroud)

要么

DoSomethingWithColors()
Run Code Online (Sandbox Code Playgroud)

那我的功能应该是什么样的?

public void DoSomethingWithColors(EnumColors someColors = ??)
 {
  ...
  }
Run Code Online (Sandbox Code Playgroud)

Mih*_*kov 9

是的,它可以是可选的.

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

public  void Func(Flags f = (Flags.F1 | Flags.F2)) {
    // body
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用或不使用参数调用您的函数.如果你在没有任何参数(Flags.F1 | Flags.F2)的情况下调用它,你将获得传递给f参数的默认值

如果您不想拥有默认值但参数仍然是可选的,则可以执行此操作

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

    }
}
Run Code Online (Sandbox Code Playgroud)


xan*_*tos 5

An enum是值类型,因此您可以使用可为空的值类型EnumColors?...

void DoSomethingWithColors(EnumColors? colors = null)
{
    if (colors != null) { Console.WriteLine(colors.Value); }
}
Run Code Online (Sandbox Code Playgroud)

然后将默认值设置EnumColors?null

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

void DoSomethingWithColors(EnumColors colors = (EnumColors)int.MinValue)
{
    if (colors != (EnumColors)int.MinValue) { Console.WriteLine(colors); }
}
Run Code Online (Sandbox Code Playgroud)