我已经添加了一个公共的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