c# - C# 名称在当前上下文中不存在
问题描述
下面是我的主要代码下面的代码块是我的书类。我对 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);
}
}
}
解决方案
printInformation
方法在Book
类中声明为static
,因此您需要指定类型名称来调用它:
Book.printInformation(book.Title, book.Author, book.Price, book.ISBN);
顺便说一句,你不需要这个方法,如果你想要 a 的字符串表示Book
,更好的方法是覆盖类ToString
中的方法Book
。
推荐阅读
- java - 出于某种原因使用 .setText() 时重叠
- java - 当我试图获取网页的损坏链接时,没有在 webdriver java 中获取所有链接
- microsoft-teams - Power Automate - 在自适应卡片中使用变量
- elasticsearch - 用户:anonymous is not authorized" 执行 es:ESHttpGet
- python - 如何通过 PuTTY 使用 sudo 命令
- c# - 不知道如何解决“非泛型类型 'ArrayList' 不能与类型参数一起使用”?
- python-3.x - 减去多列数据框和单值数据框
- css - React Native ScrollView 与相对于屏幕大小的绝对定位的子项
- c# - 使用 EF Core 继承时如何避免重复属性投影?
- powerpivot - 具有来自多个表的组合度量的 Power Pivot