C#進階(六)介面,介面繼承

來源:互聯網
上載者:User

介面我們在前面也已經有所提及。介面的命名傳統上都以大寫I 開頭。

我們假設這樣一種情況,一個系統有很多使用者,我們可以查詢某個使用者是否存在,並且可以修改使用者 的密碼。但有可能某天我們的資料庫從mysql 升級成為 sqlserver 。在這種情況下,我們看下面一個例 子。

using System;
namespace gosoa.com.cn
{
public interface IUserOperation
{
bool userExites(string username);
bool updateUserPwd(string newPwd,string oldPwd);
}
public class SqlUserOperation: IUserOperation
{
//這裡我們假使 uname oldPwd 是通過sql在資料庫中查到的。具體查詢,這裡就不說了。
string uname="pan";
public string oldPwd="gosoa.com.cn";
public bool userExites(string username)
{
if(username==uname)
{
return true;
}else
{
return false;
}
}
public bool updateUserPwd(string newPwd,string oldPwd)
{
if(newPwd==oldPwd)
{
return true;
}else
{
return false;
}
}
}
public class MainClass
{
static void Main(string [] args)
{
string newPwd =Console.ReadLine();
string username =Console.ReadLine();
SqlUserOperation one=new SqlUserOperation();
IUserOperation tow=new SqlUserOperation();
if(tow.userExites(username))
{
Console.WriteLine("使用者存在");
}else
{
Console.WriteLine("使用者不存在");
}
if(tow.updateUserPwd(newPwd,one.oldPwd))
{
Console.WriteLine("密碼修改成功");
}else
{
Console.WriteLine("密碼修改失敗");
}
}
}
/*
//我們可能某天需要用mysql 資料庫了。這時候的具體實現又有所不同了。
public class MysqlUserOperation: IUserOperation
{
}
*/
}

注意,實現介面的類,必須實作類別的全部成員。否則會報錯喔。

我們來看這一句IUserOperation tow=new SqlUserOperation(); 該句把引用變數聲明為 IUserOperation的引用方式,這表示,他們可以指向實現這個介面的任何類的執行個體。

同時,介面也可以彼此繼承,但要注意,實現介面的類必須實現介面以及介面的父介面的所有方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.