这里还有一个问题,我想解释一下。在第 47 行,我收到错误消息:
Error CS0122: 'PROPERTY NAMES' is inaccessible due to its protection level (CS0122)
问题是为什么会出错,我该如何避免呢?如果我正确地完成了这项作业。如果我应该调用属性或变量?我猜是为了属性。
附言。代码尚未完成。
注意!我的教授给了我们类图,告诉我们哪些属性应该到位,哪些属性应该获取/设置,哪些只是设置。
代码问题:
public void display()
{
Console.Write("{0}\n{1}\n{2}\n{3}", Title, getAuthorName(), PublisherName, Price);
}
完整代码:
using System;
namespace Lab_3
{
class BookTest
{
static void Main(string[] args)
{
Book book1 = new Book();
Book book2 = new Book("Advenced C#", "Joe", "Robertson", 29.99f, "PUC Press");
}
}
public class Book
{
string authorFirstName;
string authorLastName;
float price;
string publisherName;
string title;
public Book()
{
Console.Write("Enter book title: ");
Title = Console.ReadLine();
Console.Write("Enter author's first name: ");
AuthorFirstName = Console.ReadLine();
Console.Write("Enter author's last name: ");
AuthorLastName = Console.ReadLine();
Console.Write("Enter price: ");
Price = float.Parse(Console.ReadLine());
Console.Write("Enter publisher's name: ");
PublisherName = Console.ReadLine();
}
public Book(string bookTitle, string firstName, string lastName, float bookPrice, string publisher)
{
authorFirstName = firstName;
authorLastName = lastName;
price = bookPrice;
publisherName = publisher;
title = bookTitle;
}
public void display()
{
Console.Write("{0}\n{1}\n{2}\n{3}", Title, getAuthorName, PublisherName, Price);
}
public string getAuthorName()
{
return AuthorFirstName + AuthorLastName;
}
public string AuthorFirstName
{
get
{
return authorFirstName;
}
set
{
authorFirstName = value;
}
}
public string AuthorLastName
{
get
{
return authorLastName;
}
set
{
authorLastName = value;
}
}
public float Price
{
set
{
price = value;
}
}
public string PublisherName
{
set
{
publisherName = value;
}
}
public string Title
{
set
{
title = value;
}
}
}
}
编辑:已解决!谢谢大家的帮助。
总而言之,我不能使用属性,因为有些属性是只读的,这给我带来了问题。所以我需要使用私有(private)变量来显示它们。
请您参考如下方法:
因为您所在的类(class)中有方法 display(),所以不要费心使用属性,只需使用数据成员本身,因为这可能是您的教授想要的。属性用于向您的类的用户公开数据。在您的类(class)中,您可以自由使用数据成员而无需 getter 或 setter:
Console.Write("{0}\n{1}\n{2}\n{3}", title, getAuthorName(), publisherName, price);
