c#如何顯式實(shí)現(xiàn)接口成員
本示例聲明一個(gè)接口IDimensions
和一個(gè)類 Box
,顯式實(shí)現(xiàn)了接口成員 GetLength
和 GetWidth
。 通過(guò)接口實(shí)例 dimensions
訪問(wèn)這些成員。
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í)例訪問(wèn):
//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#通過(guò)html調(diào)用WinForm的方法
這篇文章主要介紹了C#通過(guò)html調(diào)用WinForm的方法,涉及html頁(yè)面中使用JavaScript訪問(wèn)C#的相關(guān)技巧,需要的朋友可以參考下2016-04-04c#和avascript加解密之間的互轉(zhuǎn)代碼分享
這篇文章主要介紹了c#和Javascript間互轉(zhuǎn)的Xxtea加解密代碼,需要的朋友可以參考下2014-02-02C#編程報(bào)錯(cuò)System.InvalidOperationException問(wèn)題及解決
這篇文章主要介紹了C#編程報(bào)錯(cuò)System.InvalidOperationException問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05c# 實(shí)現(xiàn)語(yǔ)音聊天的實(shí)戰(zhàn)示例
這篇文章主要介紹了c# 實(shí)現(xiàn)語(yǔ)音聊天的實(shí)戰(zhàn)示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-02-02C# 屏蔽關(guān)鍵字的實(shí)現(xiàn)方法
前段時(shí)間在公司做了一個(gè)論壇屏蔽關(guān)鍵字的功能,我做的比較簡(jiǎn)單、實(shí)用~ 現(xiàn)在拿出來(lái)給博友們分享下..也希望大家能頂頂我~2013-05-05C#實(shí)現(xiàn)PDF頁(yè)面合并的示例代碼
這篇文章主要為大家介紹了如何利用C#及vb.net來(lái)實(shí)現(xiàn)合并PDF頁(yè)面內(nèi)容,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定幫助,感興趣的小伙伴可以了解一下2022-04-04