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;
    }
}

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

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

我该如何解决这个错误?

4

2 回答 2

27

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

你可以像这样解决它:

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;
  }
}
于 2011-06-18T19:38:44.950 回答
4

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

于 2012-04-10T22:56:49.160 回答