c#如何顯式實(shí)現(xiàn)接口成員
本示例聲明一個(gè)接口IDimensions 和一個(gè)類 Box,顯式實(shí)現(xiàn)了接口成員 GetLength 和 GetWidth。 通過接口實(shí)例 dimensions 訪問這些成員。
interface IDimensions
{
float GetLength();
float GetWidth();
}
class Box : IDimensions
{
float lengthInches;
float widthInches;
Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
// Explicit interface member implementation:
float IDimensions.GetLength()
{
return lengthInches;
}
// Explicit interface member implementation:
float IDimensions.GetWidth()
{
return widthInches;
}
static void Main()
{
// Declare a class instance box1:
Box box1 = new Box(30.0f, 20.0f);
// Declare an interface instance dimensions:
IDimensions dimensions = box1;
// The following commented lines would produce compilation
// errors because they try to access an explicitly implemented
// interface member from a class instance:
//System.Console.WriteLine("Length: {0}", box1.GetLength());
//System.Console.WriteLine("Width: {0}", box1.GetWidth());
// Print out the dimensions of the box by calling the methods
// from an instance of the interface:
System.Console.WriteLine("Length: {0}", dimensions.GetLength());
System.Console.WriteLine("Width: {0}", dimensions.GetWidth());
}
}
/* Output:
Length: 30
Width: 20
*/
可靠編程
- 請(qǐng)注意,注釋掉了
Main方法中以下行,因?yàn)樗鼈儗a(chǎn)生編譯錯(cuò)誤。 顯式實(shí)現(xiàn)的接口成員不能從類實(shí)例訪問:
//System.Console.WriteLine("Length: {0}", box1.GetLength());
//System.Console.WriteLine("Width: {0}", box1.GetWidth());
- 另請(qǐng)注意
Main方法中的以下行成功輸出了框的尺寸,因?yàn)檫@些方法是從接口實(shí)例調(diào)用的:
System.Console.WriteLine("Length: {0}", dimensions.GetLength());
System.Console.WriteLine("Width: {0}", dimensions.GetWidth());
以上就是c#如何顯式實(shí)現(xiàn)接口成員的詳細(xì)內(nèi)容,更多關(guān)于c# 顯式實(shí)現(xiàn)接口成員的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
c#和avascript加解密之間的互轉(zhuǎn)代碼分享
這篇文章主要介紹了c#和Javascript間互轉(zhuǎn)的Xxtea加解密代碼,需要的朋友可以參考下2014-02-02
C#編程報(bào)錯(cuò)System.InvalidOperationException問題及解決
這篇文章主要介紹了C#編程報(bào)錯(cuò)System.InvalidOperationException問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
c# 實(shí)現(xiàn)語音聊天的實(shí)戰(zhàn)示例
這篇文章主要介紹了c# 實(shí)現(xiàn)語音聊天的實(shí)戰(zhàn)示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-02-02
C# 屏蔽關(guān)鍵字的實(shí)現(xiàn)方法
前段時(shí)間在公司做了一個(gè)論壇屏蔽關(guān)鍵字的功能,我做的比較簡(jiǎn)單、實(shí)用~ 現(xiàn)在拿出來給博友們分享下..也希望大家能頂頂我~2013-05-05

