c# 接口interface基礎(chǔ)入門小例子
更新時間:2013年04月21日 20:32:07 作者:
用于描述類的功能,類似于契約,指示了類將:執(zhí)行的工作,形參類型,返回結(jié)果類型,但本身沒有執(zhí)行的代碼
復(fù)制代碼 代碼如下:
/// <summary>
/// interface
/// 與抽象類的區(qū)別:
/// 1,abstract可以有具體方法和抽象方法(必須有一個抽象方法),interface沒有方法實(shí)現(xiàn)
/// 2,abstract可以有構(gòu)造函數(shù)和析構(gòu)函數(shù),接口不行
/// 3,一個類可以實(shí)現(xiàn)多個interface,但只能繼承一個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();
}
復(fù)制代碼 代碼如下:
/// <summary>
/// interface實(shí)現(xiàn)interface
/// </summary>
interface IManager:IPerson
{
string Dept { get; set; }
}
/// <summary>
/// 實(shí)現(xiàn)多個interface
/// 實(shí)現(xiàn)哪個interface必須寫全實(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";
}
}
復(fù)制代碼 代碼如下:
/// <summary>
/// 重寫接口實(shí)現(xiàn):
/// 如下,類 Employer 實(shí)現(xiàn)了IPerson,其中方法 Age() 標(biāo)記為virtual,所以繼承于 Employer 的類可以重寫 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是父類
}
}
實(shí)現(xiàn),對象與實(shí)例:
復(fù)制代碼 代碼如下:
#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; //可以通過一個實(shí)例來強(qiáng)制轉(zhuǎn)換一個接口的實(shí)例,進(jìn)而訪問其成員,
ip.Age();
DateTime x=ip.Brith;
//也可以寫成這樣:
IPerson ip2 = (IPerson) new Employee();
//但是這樣子有時候不是很安全,我們一般用is 和 as來強(qiáng)制轉(zhuǎn)換:
if (eaji is IPerson)
{
IPerson ip3 = (IPerson)eaji;
}
//但is并不是很高效,最好就是用as:
IPerson ip4 = eaji as IPerson;
if (ip4 != null)//用as時,如果發(fā)現(xiàn)實(shí)現(xiàn)ip4的類沒有繼承 IPerson,就會返回null
{
Console.WriteLine(ip4.Age());
}
#endregion
相關(guān)文章
C#基于SQLiteHelper類似SqlHelper類實(shí)現(xiàn)存取Sqlite數(shù)據(jù)庫的方法
這篇文章主要介紹了C#基于SQLiteHelper類似SqlHelper類實(shí)現(xiàn)存取Sqlite數(shù)據(jù)庫的方法,涉及C#操作SQLite數(shù)據(jù)庫的相關(guān)技巧,需要的朋友可以參考下2015-06-06
C# System.TypeInitializationException 異常處理方案
這篇文章主要介紹了C# System.TypeInitializationException 異常處理方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
C#使用TimeSpan時間計算的簡單實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于C#使用TimeSpan時間計算的相關(guān)資料,以及通過一個實(shí)例代碼給大家介紹了C#使用timespan和timer完成一個簡單的倒計時器的方法,需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06

