c#如何顯式實現(xiàn)接口成員
更新時間:2020年10月14日 08:35:41 作者:olprod
這篇文章主要介紹了c#如何顯式實現(xiàn)接口成員,幫助大家更好的利用c#處理接口,感興趣的朋友可以了解下
本示例聲明一個接口IDimensions 和一個類 Box,顯式實現(xiàn)了接口成員 GetLength 和 GetWidth。 通過接口實例 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方法中以下行,因為它們將產(chǎn)生編譯錯誤。 顯式實現(xiàn)的接口成員不能從類實例訪問:
//System.Console.WriteLine("Length: {0}", box1.GetLength());
//System.Console.WriteLine("Width: {0}", box1.GetWidth());
- 另請注意
Main方法中的以下行成功輸出了框的尺寸,因為這些方法是從接口實例調(diào)用的:
System.Console.WriteLine("Length: {0}", dimensions.GetLength());
System.Console.WriteLine("Width: {0}", dimensions.GetWidth());
以上就是c#如何顯式實現(xiàn)接口成員的詳細內(nèi)容,更多關(guān)于c# 顯式實現(xiàn)接口成員的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
c#和avascript加解密之間的互轉(zhuǎn)代碼分享
這篇文章主要介紹了c#和Javascript間互轉(zhuǎn)的Xxtea加解密代碼,需要的朋友可以參考下2014-02-02
C#編程報錯System.InvalidOperationException問題及解決
這篇文章主要介紹了C#編程報錯System.InvalidOperationException問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

