c# 接口interface基礎(chǔ)入門小例子
更新時間:2013年04月21日 20:32:07 作者:
用于描述類的功能,類似于契約,指示了類將:執(zhí)行的工作,形參類型,返回結(jié)果類型,但本身沒有執(zhí)行的代碼
復(fù)制代碼 代碼如下:
/// <summary>
/// interface
/// 與抽象類的區(qū)別:
/// 1,abstract可以有具體方法和抽象方法(必須有一個抽象方法),interface沒有方法實現(xiàn)
/// 2,abstract可以有構(gòu)造函數(shù)和析構(gòu)函數(shù),接口不行
/// 3,一個類可以實現(xiàn)多個interface,但只能繼承一個abstract
/// 特點:
/// interface成員隱式具有public,所以不加修飾符
/// 不可以直接創(chuàng)建接口的實例,如: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實現(xiàn)interface
/// </summary>
interface IManager:IPerson
{
string Dept { get; set; }
}
/// <summary>
/// 實現(xiàn)多個interface
/// 實現(xiàn)哪個interface必須寫全實現(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>
/// 重寫接口實現(xiàn):
/// 如下,類 Employer 實現(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是父類
}
}
實現(xiàn),對象與實例:
復(fù)制代碼 代碼如下:
#region #interface
Employee eaji = new Employee()
{
Name = "aji",
Brith = new DateTime(1991,06,26),
};
#endregion
#region #interface 的強制轉(zhuǎn)換
IPerson ip = (IPerson)eaji; //可以通過一個實例來強制轉(zhuǎn)換一個接口的實例,進(jìn)而訪問其成員,
ip.Age();
DateTime x=ip.Brith;
//也可以寫成這樣:
IPerson ip2 = (IPerson) new Employee();
//但是這樣子有時候不是很安全,我們一般用is 和 as來強制轉(zhuǎn)換:
if (eaji is IPerson)
{
IPerson ip3 = (IPerson)eaji;
}
//但is并不是很高效,最好就是用as:
IPerson ip4 = eaji as IPerson;
if (ip4 != null)//用as時,如果發(fā)現(xiàn)實現(xiàn)ip4的類沒有繼承 IPerson,就會返回null
{
Console.WriteLine(ip4.Age());
}
#endregion
相關(guān)文章
C#使用FluentScheduler實現(xiàn)觸發(fā)定時任務(wù)
FluentScheduler是.Net平臺下的一個自動任務(wù)調(diào)度組件,這篇文章主要為大家詳細(xì)介紹了C#如何使用FluentScheduler實現(xiàn)觸發(fā)定時任務(wù),感興趣的小伙伴可以了解下2023-12-12
C#使用SqlDataAdapter對象獲取數(shù)據(jù)的方法
這篇文章主要介紹了C#使用SqlDataAdapter對象獲取數(shù)據(jù)的方法,結(jié)合實例形式較為詳細(xì)的分析了SqlDataAdapter對象獲取數(shù)據(jù)具體步驟與相關(guān)使用技巧,需要的朋友可以參考下2016-02-02
解析C#編程的通用結(jié)構(gòu)和程序書寫格式規(guī)范
這篇文章主要介紹了C#編程的通用結(jié)構(gòu)和程序書寫格式規(guī)范,這里我們根據(jù)C#語言的開發(fā)方微軟給出的約定來作為編寫樣式參照,需要的朋友可以參考下2016-01-01
C#使用ToUpper()與ToLower()方法將字符串進(jìn)行大小寫轉(zhuǎn)換的方法
這篇文章主要介紹了C#使用ToUpper()與ToLower()方法將字符串進(jìn)行大小寫轉(zhuǎn)換的方法,實例分析了C#大小寫轉(zhuǎn)換的相關(guān)技巧,需要的朋友可以參考下2015-04-04

