【问题标题】:Error CS7036 There is no argument given that corresponds to the required formal parameter错误 CS7036 没有给出与所需形式参数相对应的参数
【发布时间】:2019-10-14 21:45:59
【问题描述】:

我在标题中遇到错误,谁能告诉我我的代码有什么问题?

public class Book
{
    public string Distributor { get; set; }
    public string Name { get; set; }
    public int Amount { get; set; }
    public double Price { get; set; }
    public Book(string distributor, string name, int amount, double price)
    {
        this.Distributor = distributor;
        this.Name = name;
        this.Amount = amount;
        this.Price = price;
    }
    public override string ToString()
    {
        string line = string.Format("| {0,15} | {1,15} | {2,5} | {3,6} |", Distributor, Name, Amount, Price);
        return line;
    }
    public override bool Equals(object obj)
    {
        Book book = obj as Book;
        return book.Price == Price;
    }
    public override int GetHashCode()
    {
        return Price.GetHashCode();
    }
    public static Book operator >= (Book book1, Book book2) //the error here
    {
        Book temp = new Book();
        if (book1.Name == book2.Name && book1.Price > book2.Price)
            temp = book1;
        return temp;
    }
    public static Book operator <= (Book book1, Book book2) // and here
    {
        Book temp = new Book();
        if (book1.Name == book2.Name && book1.Price < book2.Price)
            temp = book2;
        return temp;
    }
}

我在“操作员”行中遇到错误。我希望运算符 '>=' 和 '

【问题讨论】:

  • 您没有接受零参数的 Book 构造函数。编译器的错误信息中明确说明。
  • 我需要什么构造器?
  • 您需要一个空的构造函数 public Book() { } 通常这个空的构造函数是自动定义的,但是当您创建自己的构造函数时,它就不会再自动添加了
  • &gt;=&lt;= 运算符应该返回bool,而不是Book。这也应该解决您的构造函数问题,因为您不会在运算符内部创建一本书。

标签: c# operators


【解决方案1】:

我希望运算符 '>=' 和 '

这不是那些运营商所做的。它们会告诉您一个值是否小于/大于或等于另一个值。因此,他们应该返回bool 而不是Book。如果它们具有不同的名称,您还需要决定返回什么:

public static bool operator >= (Book book1, Book book2)
{
    if (book1.Name == book2.Name)
       return (book1.Price >= book2.Price);
    else
       return ?? what do you want to return here ??
}
public static bool operator <= (Book book1, Book book2)
{
    if (book1.Name == book2.Name)
       return (book1.Price <= book2.Price);
    else
       return ?? what do you want to return here ??
}

如果这确实是您想要做的,那么我鼓励您也重载 &lt;&gt; 运算符。

【讨论】:

  • 还应该以某种方式定义空检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 2019-10-22
  • 2017-07-18
  • 1970-01-01
  • 2019-06-30
  • 2016-05-13
相关资源
最近更新 更多