【问题标题】:Default parameter must be compile-time constant默认参数必须是编译时常量
【发布时间】:2014-06-25 21:45:21
【问题描述】:

我想创建一个具有可选参数的方法。我正在编写的程序需要这些是 DateTime 形式。我当前的方法声明是

public void UpdateTable(int month = DateTime.Now.Month, int year = DateTime.Now.Year)
    {
        // Code here.
    }

但是,我收到此错误“'month' 的默认参数值必须是编译时常量。”

如何解决此错误?在调用它之前,我是否需要在方法之外设置这些值?

【问题讨论】:

  • DateTime.Now 取决于它在执行过程中何时被调用,因此它不是编译时常量。

标签: c# datetime compiler-errors


【解决方案1】:

如果您不想事先设置它,我认为您必须传入一组不同的默认值:

    public void UpdateTable(int month = -1, int year = -1)
    {
        if (month == -1) month = DateTime.Now.Month;
        if (year == -1) year = DateTime.Now.Year;
    }

【讨论】:

    【解决方案2】:

    DateTime.Now当然会在每次程序运行时都不一样——所以不能作为默认值。

    解决此问题的一种方法是使用具有不同参数计数的重载函数。

    public void UpdateTable(int month, int year)
    {
        // Code here.
    }
    
    public void UpdateTable(int month)
    {
        // fill in the current year
        UpdateTable(month, DateTime.Now.Year);
    }
    
    public void UpdateTable()
    {
        // fill in the current month / year
        UpdateTable(DateTime.Now.Month, DateTime.Now.Year);
    }
    

    【讨论】:

      【解决方案3】:

      你不能那样做。如错误所示,可选参数的默认值必须在编译时确定。

      您可以使用nullable type (int?),如下所示:

      public void UpdateTable(int? month = null, int? year = null)
      {
          month = month ?? DateTime.Now.Month;
          year = year ?? DateTime.Now.Year;
          // Code here.
      }
      

      但我建议进行重载,如下所示:

      public void UpdateTable(int month, int year)
      {
          // Code here.
      }
      public void UpdateTable(int month)
      {
          UpdateTable(month, DateTime.Now.Year);
      }
      public void UpdateTable()
      {
          UpdateTable(DateTime.Now.Month, DateTime.Now.Year);
      }
      

      【讨论】:

      • 如果您希望能够仅传递月份或年份怎么办?您不能有两个采用相同参数集的重载。这就是默认值如此有用的原因。您可以更好地控制发送的参数。
      • @Francine 是的,这取决于 OP 正在构建的 API 类型。这就是为什么我包括两个选项。如果是我的代码,我还会考虑使用两种不同的方法,UpdateTableMonthUpdateTableYear 以完全避免混淆,或者更好的是,如果可能的话,使用一个采用 DateTime 的单一方法。
      【解决方案4】:

      .Now 不是常量,因此不能将其用作默认值。

      我建议默认为null,然后如果值为null,则在运行时获取默认值。

      public void UpdateTable(int? month = null, int? year = null)
      {
         month = month ?? DateTime.Now.Month;
         year = year ?? DateTime.Now.Year;
         // Code here.
      }
      

      【讨论】:

      • 这条线是做什么的?月=月?? DateTime.Now.Month?;
      • @Ultra 你问的是空合并运算符 (??) 吗? msdn.microsoft.com/en-us/library/ms173224.aspx
      • ?? // 总结:如果左操作数不为空,则返回左操作数。如果左操作数为空,则返回右操作数。所以,对于“月=月??DateTime.Now.Month;”行,如果月份为空,则将月份设置为DateTime.Now.Month,如果月份不为空,则保持不变。
      • @Ben 抱歉没有具体说明。这就是我要问的。谢谢你的回答!
      猜你喜欢
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      相关资源
      最近更新 更多