/// <summary>
/// interface
/// 與抽象類(lèi)的區(qū)別:
/// 1,abstract可以有具體方法和抽象方法(必須有一個(gè)抽象方法),interface沒(méi)有方法實(shí)現(xiàn)
/// 2,abstract可以有構(gòu)造函數(shù)和析構(gòu)函數(shù),接口不行
/// 3,一個(gè)類(lèi)可以實(shí)現(xiàn)多個(gè)interface,但只能繼承一個(gè)abstract
/// 特點(diǎn):
/// interface成員隱式具有public,所以不加修飾符
/// 不可以直接創(chuàng)建接口的實(shí)例,如:IPerson xx=new IPerson()//error
/// </summary>
public interface IPerson
{
string Name { get; set; }//特性
DateTime Brith { get; set; }
int Age();//函數(shù)方法
}
interface IAdderss
{
uint Zip { get; set; }
string State();
}
/// <summary>
/// interface實(shí)現(xiàn)interface
/// </summary>
interface IManager:IPerson
{
string Dept { get; set; }
}
/// <summary>
/// 實(shí)現(xiàn)多個(gè)interface
/// 實(shí)現(xiàn)哪個(gè)interface必須寫(xiě)全實(shí)現(xiàn)的所有成員!
/// </summary>
public class Employee:IPerson,IAdderss
{
public string Name { get; set; }
public DateTime Brith { get; set; }
public int Age()
{
return 10;
throw new NotImplementedException();
}
public uint Zip { get; set; }
public string State()
{
return "alive";
}
}
/// <summary>
/// 重寫(xiě)接口實(shí)現(xiàn):
/// 如下,類(lèi) Employer 實(shí)現(xiàn)了IPerson,其中方法 Age() 標(biāo)記為virtual,所以繼承于 Employer 的類(lèi)可以重寫(xiě) Age()
///
/// </summary>
public class Employer:IPerson
{
public string Name { get; set; }
public DateTime Brith { get; set; }
public virtual int Age()
{
return 10;
}
}
public class work:Employer
{
public override int Age()
{
return base.Age()+100;//其中base是父類(lèi)
}
}
實(shí)現(xiàn),對(duì)象與實(shí)例:
#region #interface
Employee eaji = new Employee()
{
Name = "aji",
Brith = new DateTime(1991,06,26),
};
#endregion
#region #interface 的強(qiáng)制轉(zhuǎn)換
IPerson ip = (IPerson)eaji; //可以通過(guò)一個(gè)實(shí)例來(lái)強(qiáng)制轉(zhuǎn)換一個(gè)接口的實(shí)例,進(jìn)而訪(fǎng)問(wèn)其成員,
ip.Age();
DateTime x=ip.Brith;
//也可以寫(xiě)成這樣:
IPerson ip2 = (IPerson) new Employee();
//但是這樣子有時(shí)候不是很安全,我們一般用is 和 as來(lái)強(qiáng)制轉(zhuǎn)換:
if (eaji is IPerson)
{
IPerson ip3 = (IPerson)eaji;
}
//但is并不是很高效,最好就是用as:
IPerson ip4 = eaji as IPerson;
if (ip4 != null)//用as時(shí),如果發(fā)現(xiàn)實(shí)現(xiàn)ip4的類(lèi)沒(méi)有繼承 IPerson,就會(huì)返回null
{
Console.WriteLine(ip4.Age());
}
#endregion