【发布时间】:2014-05-04 00:26:21
【问题描述】:
我正在学习 C#(不是家庭作业)。不知道为什么我的 TextBook 和 CoffeeTableBook 子类中跳过了我的“公共新双倍价格”。我认为这是由于我的构造函数,因为这是在退出类之前执行的最后一行代码。还没有学到太花哨的东西,寻求简单。谢谢。
namespace BookDemo
{
class Program
{
static void Main()
{
Book book1 = new Book (123, "BOOK: The Blue Whale", "Liam Smith", 15.99);
Book book2 = new Book(456, "BOOK: The Blue Whale 2", "Liam Smith", 35.00);
TextBook book3 = new TextBook(789, "TEXTBOOK: Math 101", "Bob Taylor", 1000.00, 10);
CoffeeTableBook book4 = new CoffeeTableBook(789, "TEXTBOOK: Math 101", "Molly Burns", 0.10);
Console.WriteLine(book1.ToString());
Console.WriteLine(book2.ToString());
Console.WriteLine(book3.ToString());
Console.WriteLine(book4.ToString());
Console.ReadLine();
}
class Book
{
private int Isbn { get; set; }
private string Title { get; set; }
private string Author { get; set; }
protected double Price { get; set; }
//Book Constructor
public Book(int isbn, string title, string author, double price)
{
Isbn = isbn;
Title = title;
Author = author;
Price = price;
}
public override string ToString()
{
return("\n" + GetType() + "\nISBN: " + Isbn + "\nTitle: " + Title + "\nAuthor: " + Author + "\nPrice: " + Price.ToString("C2"));
}
}
class TextBook : Book
{
private const int MIN = 20;
private const int MAX = 80;
private int GradeLevel { get; set; }
//TextBook Constructor
public TextBook(int isbn, string title, string author, double price, int grade) : base (isbn, title, author, price)
{
GradeLevel = grade;
}
public new double Price
{
set
{
if (value <= MIN)
Price = MIN;
if (value >= MAX)
Price = MAX;
else
Price = value;
}
}
}
class CoffeeTableBook : Book
{
const int MIN = 35;
const int MAX = 100;
public new double Price // min 35, max 100
{
set
{
if (value <= MIN)
Price = MIN;
if (value >= MAX)
Price = MAX;
else
Price = value;
}
}
//CoffeeTable Book Constructor
public CoffeeTableBook(int isbn, string title, string author, double price) : base (isbn, title, author, price)
{
}
}
}
}
【问题讨论】:
-
不确定您观察到的行为,但您可能正在寻找
virtual/override而不是new。查看confused about new vs. virtual -
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# inheritance overriding