下面是我的主要代码,下面的代码块是我的book类。我是c#的新手,之前没有遇到过这个错误。我在第39和48行遇到错误。两个都是printInformation()
电话。错误是
名称'printInformation'在当前上下文中不存在
我不知道该怎么做,我尝试将书类和主类中的所有代码放入一个单独的文件中,其中所有代码都在一起,并且不会出错。
这是否意味着我需要做的事情就公共和私人类所使用的还是别的。我有值title
,author
,price
和isbn
的公共getter和setter。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the amount of books you have, followed by the number 1 or number 2 seperated by a space");
Console.Write("Enter 1 if you would like to sort the books by price in ascending order");
Console.WriteLine("Enter 2 if you would like to sort the books by title alphabetically.");
string number = Console.ReadLine();
string[] numberArray = number.Split(' ');
List<Book> bookList = new List<Book>();
// for the number entered input values
for (int i = 0; i < Convert.ToInt16(numberArray[0]); i++)
{
bookList.Add(new Book
{
Title = Console.ReadLine(),
Author = Console.ReadLine(),
Price = Convert.ToDouble(Console.ReadLine()),
ISBN = Console.ReadLine()
});
}
// sorting based on condition given
if (Convert.ToInt16(numberArray[1]) == 1)
{
var sortedList = from book in bookList orderby book.Price select book;
foreach (var book in sortedList)
{
printInformation(book.Title, book.Author, book.Price, book.ISBN);
}
}
else
{
var sortedList = from book in bookList orderby book.Title select book;
foreach (var book in sortedList)
{
printInformation(book.Title, book.Author, book.Price, book.ISBN);
}
}
// added this to hold the console window
Console.ReadLine();
}
}
}
预订课程:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Book
{
// private fields
private string title;
private string author;
private double price;
private string isbn;
public static void printInformation(string _title, string _author, double _price, string _isbn)
{
Console.WriteLine(_title + " written by " + _author + " is " + _price.ToString() + " dollars, with ISBN " + _isbn);
}
}
}
printInformation
方法在Book
类中声明为static
,因此您需要调用它来指定类型名称:
Book.printInformation(book.Title, book.Author, book.Price, book.ISBN);
顺便说一句,你不需要这个方法,如果你想要一个Book
的字符串表示,更好的方法是覆盖ToString
类中的Book
方法。