我已經添加了一個公共的GetSummary方法來預訂我想返回一個包含標題,作者和作者年齡的字符串。然而,IM卡上了年紀的一部分,我知道我必須添加一些人的年齡,但不能似乎做C#打印字符串
任何幫助,將不勝感激
感謝
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Book[] books = new Book[4]; //declare an array of Book
books[0] = new Book("Moby Dick");
books[0].author = new Person("Herman Melville");
books[1] = new Horror("The Creeping");
for (int i = 0; i < 3; i++)
Console.WriteLine(books[i].GetSummary);
Console.ReadKey();
}
}
}
class Person : IComparable
{
private int age;
private string name;
//constructor with one argument
public Person(string name)
{
this.name = name;
age = 18; //default age
}
//property for name
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public int CompareTo(Object obj) //implementation of CompareTo
{ // for IComparable
Person other = (Person)obj;
return Name.CompareTo(other.Name); //uses Name for comparison
}
}
}
class Horror : Book
{
public Horror(string title): base(title)
{
base.author = new Person("Stephen King");
}
}
}
class Book
{
public string title;
public Person author;
public Book(string title)
{
author = new Person(" ");
this.title = title;
}
public string AuthorName
{
get { return author.Name; }
set { author.Name = value; }
}
public string GetSummary
{
get
{
string x = title + ", " + AuthorName;
return x;
}
}
}
}
你到底在幹什麼? – 2014-10-18 14:07:28
這不是你的問題,但除非你想不斷更新數據,否則你應該刪除Age的setter,添加BirthDate屬性並從出生日期計算年齡 – 2014-10-18 14:13:22
刪除實例變量並使[Auto-Implemented Properties](http ://msdn.microsoft.com/en-us/library/bb384054.aspx)。你也不需要有AuthorName。 – NMK 2014-10-18 14:13:45