下面是我的主要代码,下面的代码块是我的书本类。我对C#相当陌生,之前从未遇到过此错误。我在第39行和第48行上遇到错误。这两个都是printInformation()
调用。错误是
名称“ printInformation”在当前上下文中不存在
我不确定该怎么办,我尝试将book类和main类中的所有代码放入一个单独的文件中,其中所有代码都在一起,并且不会出错。
这是否意味着我需要对使用的公共和私有类做些什么,还是其他?我有用于值title
,author
,price
和isbn
的公共获取器和设置器。
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);
}
}
}
答案 0 :(得分:1)
printInformation
方法在Book
类中声明为static
,因此您需要指定类型名称来调用它:
Book.printInformation(book.Title, book.Author, book.Price, book.ISBN);
顺便说一句,您不需要此方法,如果要使用Book
的字符串表示形式,则更好的方法是在ToString
类中重写Book
方法。 / p>