c#如何顯式實(shí)現(xiàn)接口成員
本示例聲明一個接口IDimensions 和一個類 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
*/
可靠編程
- 請注意,注釋掉了
Main方法中以下行,因?yàn)樗鼈儗a(chǎn)生編譯錯誤。 顯式實(shí)現(xiàn)的接口成員不能從類實(shí)例訪問:
//System.Console.WriteLine("Length: {0}", box1.GetLength());
//System.Console.WriteLine("Width: {0}", box1.GetWidth());
- 另請注意
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)接口成員的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解C#中delegate/event/EventHandler/Action/Func的使用和區(qū)別
這篇文章主要為大家詳細(xì)介紹了C#中delegate、event、EventHandler、Action和Func的使用與區(qū)別,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-04-04
C#?將Excel轉(zhuǎn)為PDF時自定義表格紙張大小的代碼思路
這篇文章主要介紹了C#?將Excel轉(zhuǎn)為PDF時自定義表格紙張大小的代碼思路,轉(zhuǎn)換前的頁面大小設(shè)置為該版本中寫入的新功能,在舊版本和免費(fèi)版本中暫不支持,感興趣的朋友跟隨小編一起看看實(shí)例代碼2021-11-11
C# 獲取打印機(jī)當(dāng)前狀態(tài)的方法
C# 獲取打印機(jī)當(dāng)前狀態(tài)的方法,需要的朋友可以參考一下2013-04-04
C#.net實(shí)現(xiàn)在Winform中從internet下載文件的方法
這篇文章主要介紹了C#.net實(shí)現(xiàn)在Winform中從internet下載文件的方法,實(shí)例分析了基于Winform實(shí)現(xiàn)文件下載的相關(guān)技巧,需要的朋友可以參考下2015-07-07
C#實(shí)現(xiàn)基于ffmpeg加虹軟的人臉識別的示例
本篇文章主要介紹了C#實(shí)現(xiàn)基于ffmpeg加虹軟的人臉識別的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
解析數(shù)字簽名的substring結(jié)構(gòu)(獲取數(shù)字簽名時間)
解析數(shù)字簽名的substring結(jié)構(gòu),大家參考使用吧2013-12-12

