【问题标题】:Compiler error "Default parameter specifiers are not permitted"编译器错误“不允许使用默认参数说明符”
【发布时间】:2011-09-17 21:49:16
【问题描述】:

下面是我的代码。

public class PItem
{
    public String content;
    public int count;
    public int fee;
    public int amount;
    public string description;

    // Default values
    public PItem(String _content = "", int _count = 0, int _fee = 0, string _description = "", int _amount = 0)
    {
        content = _content;
        count = _count < 0 ? 0 : _count;
        fee = _fee;
        description = _description;
        amount = _amount < 0 ? 0 : _amount;
    }
}

这是在一个类里面。当我尝试运行一个程序时,它给出了这个错误:

不允许使用默认参数说明符

我该如何解决这个错误?

【问题讨论】:

  • 你怎么知道你使用的是 C# 4.0?
  • 这个错误发生在哪里?编译时?
  • yes akash.. 在编译时我遇到了这个错误
  • Gabe 对 C# 4.0 感到抱歉...我该如何解决我的问题
  • @hesamsalehnamadi:既然您已经解决了您的问题,您可能需要考虑通过编辑甚至删除您的问题来回馈一点,因为它具有误导性(您没有使用 C# 4)。跨度>

标签: c# compiler-errors .net-3.5 default-parameters


【解决方案1】:

问题是在低于 4 的 C# 版本中不能有可选参数。
您可以在此here 上找到更多信息。

你可以这样解决:

public class PItem
{
  public String content;
  public int count;
  public int fee;
  public int amount;
  public String description;
  // default values
  public PItem(): this("", 0, 0, "", 0) {}
  public PItem(String _content): this (_content, 0, 0, "", 0) {}
  public PItem(String _content, int _count): this(_content, _count, 0, "", 0) {}
  public PItem(String _content, int _count, int _fee): this(_content, _count, _fee, "", 0) {}
  public PItem(String _content, int _count, int _fee, string _description): this(_content, _count, _fee, _description, 0) {}
  public PItem(String _content, int _count, int _fee, string _description, int _amount)
  {
      content = _content;
      count = _count < 0 ? 0 : _count;
      fee = _fee;
      description = _description;
      amount = _amount < 0 ? 0 : _amount;
  }
}

【讨论】:

  • -1:这是虚假信息。文档 (msdn.microsoft.com/en-us/library/dd264739.aspx) 明确指出“方法、构造函数、索引器或委托的定义可以指定其参数是必需的还是可选的。”
  • @Jon: 措辞改变了...更好?
  • 确实更好。虽然不幸的是,这整个问题是一场惨败。
【解决方案2】:

如果您的项目似乎设置为 .NET 4.0,则将其更改为例如 3.5,然后再次更改为 4.0。当我想将项目包含在我的新软件中时,当我将一个类库项目从我的旧解决方案解决方案包含到一个新解决方案时,我得到了这个错误。两种解决方案都是 .NET 4,但出现“不允许使用默认参数说明符”错误。我只是按照我的解释做了。

【讨论】:

  • 谢谢!同样的解决方案对我有用……但一个非常奇怪的错误!
  • 这也是我的解决方案。项目是 .NET 4.5,但在我从 Github 上拉下来后第一次构建时给了我这个错误。
猜你喜欢
  • 2014-12-10
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
  • 2014-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多