编译器错误 "不允许使用默认参数说明符"。

11

以下是我的代码。

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? - Gabe
这个错误发生在哪里?是在编译时吗? - Akash Kava
是的,Akash。在编译时我遇到了这个错误。 - hesam salehnamadi
Gabe,关于C# 4.0的问题很抱歉...我该如何解决我的问题? - hesam salehnamadi
@hesamsalehnamadi:既然你已经解决了问题,考虑通过编辑或者删除问题来回馈社区吧,因为它会误导其他人(你并没有使用C# 4)。 - Jon
你的标识符下划线约定与通常含义完全相反。 - Rick Sladkey
2个回答

27

问题在于,C# 4版本以下不支持可选参数。


您可以在此处找到更多信息。

您可以像这样解决它:

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:这是错误的信息。文档(http://msdn.microsoft.com/en-us/library/dd264739.aspx)明确指出:“方法、**构造函数**、索引器或委托的定义可以指定其参数是必需的还是可选的。” - Jon
@Jon:措辞改变了...更好了吗? - Sani Huttunen
确实更好。不过不幸的是,整个问题都是一场灾难。 - Jon

4
如果你的项目设置看起来是.NET 4.0,那么请将它改为例如3.5,然后再改回4.0。当我想将旧解决方案中的类库项目包含到新解决方案中并将该项目放入新软件中时,我遇到了这个错误。两个解决方案都是.NET 4,但我遇到了“不允许默认参数修饰符”的错误。我只是按照我所解释的做了一下。

1
谢谢!同样的解决方案对我也起作用了……但是真的是一个非常奇怪的错误! - ankit0311
这也是我的解决方案。项目是.NET 4.5,但在我从Github上拉下来后第一次构建时出现了这个错误。 - Shawn South

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