c# 介面interface基礎入門小例子

來源:互聯網
上載者:User

複製代碼 代碼如下:  /// <summary>
/// interface
/// 與抽象類別的區別:
/// 1,abstract可以有具體方法和抽象方法(必須有一個抽象方法),interface沒有方法實現
/// 2,abstract可以有建構函式和解構函式,介面不行
/// 3,一個類可以實現多個interface,但只能繼承一個abstract
/// 特點:
/// interface成員隱式具有public,所以不加修飾符
/// 不可以直接建立介面的執行個體,如:IPerson xx=new IPerson()//error
/// </summary>
public interface IPerson
{
string Name { get; set; }//特性
DateTime Brith { get; set; }
int Age();//函數方法
}
interface IAdderss
{
uint Zip { get; set; }
string State();
}

複製代碼 代碼如下:   /// <summary>
/// interface實現interface
/// </summary>
interface IManager:IPerson
{
string Dept { get; set; }
}
/// <summary>
/// 實現多個interface
/// 實現哪個interface必須寫全實現的所有成員!
/// </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>
/// 重寫介面實現:
/// 如下,類 Employer 實現了IPerson,其中方法 Age() 標記為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是父類
}
}

實現,對象與執行個體:

複製代碼 代碼如下:       #region #interface

Employee eaji = new Employee()
{
Name = "aji",
Brith = new DateTime(1991,06,26),
};

#endregion
#region #interface 的強制轉換

IPerson ip = (IPerson)eaji; //可以通過一個執行個體來強制轉換一個介面的執行個體,進而訪問其成員,
ip.Age();
DateTime x=ip.Brith;

//也可以寫成這樣:
IPerson ip2 = (IPerson) new Employee();

//但是這樣子有時候不是很安全,我們一般用is 和 as來強制轉換:
if (eaji is IPerson)
{
IPerson ip3 = (IPerson)eaji;
}
//但is並不是很高效,最好就是用as:
IPerson ip4 = eaji as IPerson;
if (ip4 != null)//用as時,如果發現實現ip4的類沒有繼承 IPerson,就會返回null
{
Console.WriteLine(ip4.Age());
}

#endregion

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.