//程序清单P9_3.cs:
using System;
namespace P9_3
{
public class NewInheritSample
{
public static void Main()
{
Business c1 = new Business("李明");
c1["办公电话"] = "01060010800";
Classmate c2 = new Classmate("张鹏");
c2.Birthday = new DateTime(1977, 2, 19);
Contact c=c1;
c.Output();
Console.WriteLine();
c=c2;
c.Output();
}
}
/// <summary>
/// 基类:联系人Contact
/// </summary>
public class Contact
{
//字段
protected string m_name;
protected string m_homePhone = "未知";
protected string m_busiPhone = "未知";
protected string m_mobilePhone = "未知";
//属性
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
//索引函数
public string this[string sType]
{
get
{
string type = sType.ToUpper();
switch (type)
{
case "住宅电话":
return m_homePhone;
case "办公电话":
return m_busiPhone;
case "手机":
return m_mobilePhone;
default:
return null;
}
}
set
{
string type = sType.ToUpper();
switch (type)
{
case "住宅电话":
m_homePhone = value;
break;
case "办公电话":
m_busiPhone = value;
break;
case "手机":
m_mobilePhone = value;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
//构造函数
public Contact(string sName)
{
m_name = sName;
}
//方法
public virtual void Output()
{
Console.WriteLine("姓名: {0}", m_name);
Console.WriteLine("住宅电话: {0}", m_homePhone);
Console.WriteLine("办公电话: {0}", m_busiPhone);
Console.WriteLine("手机: {0}", m_mobilePhone);
}
}
/// <summary>
/// 派生类:商务Business
/// </summary>
public class Business : Contact
{
//字段
protected string m_busiFax = "未知";
protected string m_title = "女士/先生";
//属性
public string Title
{
get
{
return m_title;
}
set
{
m_title = value;
}
}
//索引函数
public new string this[string sType]
{
get
{
string type = sType.ToUpper();
switch (type)
{
case "商务传真":
return m_busiFax;
default:
return base[sType];
}
}
set
{
string type = sType.ToUpper();
switch (type)
{
case "商务传真":
m_busiFax = value;
break;
default:
base[sType] = value;
break;
}
}
}
//构造函数
public Business(string sName) : base(sName)
{
}
//方法
public new void Output()
{
base.Output();
Console.WriteLine("商务传真: {0}", m_busiFax);
Console.WriteLine();
}
}
/// <summary>
/// 派生类:同学Classmate
/// </summary>
public class Classmate : Contact
{
//字段
protected DateTime m_birthday;
//属性
public DateTime Birthday
{
get
{
return m_birthday;
}
set
{
m_birthday = value;
}
}
//构造函数
public Classmate(string sName) : base(sName)
{
}
//方法
public new void Output()
{
base.Output();
Console.WriteLine("生日: {0}", m_birthday);
Console.WriteLine();
}
}
}