【问题标题】:Can enum parameter be optional in c#?c#中的枚举参数可以是可选的吗?
【发布时间】:2015-03-20 08:00:28
【问题描述】:

我使用this helpful post 学习了如何将枚举值列表作为参数传递。

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

例子:

   public enum EnumColors
    {
        [Flags]
        Red = 1,
        Green = 2,
        Blue = 4,
        Black = 8
    }

我想像这样调用接收 Enum 参数的函数:

DoSomethingWithColors(EnumColors.Red | EnumColors.Blue)

DoSomethingWithColors()

我的函数应该是什么样子的?

public void DoSomethingWithColors(EnumColors someColors = ??)
 {
  ...
  }

【问题讨论】:

  • 顺便说一句,几乎每个enum 都应该为0 定义一些 值,通常对于Flags,它应该被称为None。跨度>
  • [Flags] 属性属于enum,而不是枚举字段。
  • 如果default(EnumColors)的值是他在省略可选参数时想要的值,他可以使用public void DoSomethingWithColors(EnumColors someColors = 0)public void DoSomethingWithColors(EnumColors someColors = default(EnumColors))。或者像@Damien_The_Unbeliever 说的,在枚举类型中引入None=0,,并使用public void DoSomethingWithColors(EnumColors someColors = EnumColors.None)

标签: c# enums optional-parameters


【解决方案1】:

是的,它可以是可选的。

[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) {

    }
}

【讨论】:

  • 谢谢 - 所有 cmets 都很有价值。遗憾的是,只有 1 个可以被接受,通常前 1 个会得到点头。
【解决方案2】:

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.Black)
    {
        //whatever        
    }
    

    可以这样调用它:

    colorfunc();
    colorfunc(EnumColors.Blue);
    

    【讨论】:

      【解决方案4】:

      你可以重载你的函数,所以写两个函数:

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

      【讨论】:

      • 你有一个 2009 年的电话(?),他们要求告诉你有。
      • 自 2010 年的 C# version 4 以来,C# 确实有 optional parameters
      • 首先:我在 VS2008 中工作,VB.Net 有可选参数,而不是 C#,这就是我这么认为的原因。所以我更新了我的答案。第二:我的方式更干净(对我来说),并且与以前的版本兼容。
      猜你喜欢
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 2014-02-13
      • 2011-11-28
      • 2017-11-11
      相关资源
      最近更新 更多