我制作了这段代码,它使用类来提取信息objects
。我仍然是Class
和Object programming
的新手,所以我往往会遇到错误。现在我有一个问题我绝对不明白。我尝试过全能的谷歌,用不同的操作员替换部分代码并询问我的同事程序员朋友。似乎没有人知道发生了什么。
问题发生在CompareBooks
方法中,它一直告诉我我错过了formal parameter
。有人建议在方法中使用:base
,但它只创建了2个错误。
namespace ClassProgram
{
class Book
{
public string name;
public int id;
public float price;
public void PrintBookInfo()
{
Console.WriteLine("--------------");
Console.WriteLine("Book Name: " + this.name);
Console.WriteLine("Book Id: " + this.id);
Console.WriteLine("Book Price: " + this.price + " dollars");
}
public void CompareBooks(Book book1)
{
if (this.price > book1.price)
{
Console.WriteLine(this.name + " is more expensive than " + book1.name);
}
}
class MainProgram
{
static void Main(string[] args)
{
Book book = new Book();
book.name = "C# For Newbies";
book.id = 01;
book.price = 10;
book.PrintBookInfo();
book.CompareBooks();
Book book1 = new Book();
book1.name = "Lord Of The Rings";
book1.id = 02;
book1.price = 5;
book1.PrintBookInfo();
}
}
}
}
答案 0 :(得分:3)
当您致电时,您的book.CompareBooks();
没有Book
个对象作为参数输入。将此与您的签名进行比较:
public void CompareBooks(Book book1) //the Book object is required in the input
因此你得到了错误。 "形式参数"表示 a-must 参数(与C#中的合成糖optional-parameter相比)。这意味着你必须在方法的输入参数中加入一些东西来调用它。
假设在MainProgram
中,它运行如下:
Book book = new Book();
book.name = "C# For Newbies";
book.id = 01;
book.price = 10;
book.PrintBookInfo();
Book book1 = new Book();
book1.name = "Lord Of The Rings";
book1.id = 02;
book1.price = 5;
book1.PrintBookInfo();
book.CompareBooks(book1); //note that this has input now
然后你的代码应该没问题
答案 1 :(得分:1)
您不会提供有关您的第一本书应与哪本书进行比较的任何信息。我想你会这样:
Book book = new Book();
book.name = "C# For Newbies";
book.id = 01;
book.price = 10;
book.PrintBookInfo();
Book book1 = new Book();
book1.name = "Lord Of The Rings";
book1.id = 02;
book1.price = 5;
book1.PrintBookInfo();
book.CompareBooks(book1);