Poznámka:
Přístup k této stránce vyžaduje autorizaci. Můžete se zkusit přihlásit nebo změnit adresáře.
Přístup k této stránce vyžaduje autorizaci. Můžete zkusit změnit adresáře.
Tento příklad deklaruje rozhraní a IDimensionstřídu, Boxkterá explicitně implementuje členy GetLength rozhraní a GetWidth. K členům se přistupuje prostřednictvím instance dimensionsrozhraní .
Příklad
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(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:
//Console.WriteLine($"Length: {box1.GetLength()}");
//Console.WriteLine($"Width: {box1.GetWidth()}");
// Print out the dimensions of the box by calling the methods
// from an instance of the interface:
Console.WriteLine($"Length: {dimensions.GetLength()}");
Console.WriteLine($"Width: {dimensions.GetWidth()}");
}
}
/* Output:
Length: 30
Width: 20
*/
Robustní programování
Všimněte si, že následující řádky v
Mainmetodě jsou okomentovány, protože by způsobovaly chyby kompilace. Člen rozhraní, který je explicitně implementován, nelze přistupovat z instance té třídy.//Console.WriteLine($"Length: {box1.GetLength()}"); //Console.WriteLine($"Width: {box1.GetWidth()}");Všimněte si také, že následující řádky v
Mainmetodě úspěšně vytisknou rozměry rámečku, protože metody jsou volány z instance rozhraní:Console.WriteLine($"Length: {dimensions.GetLength()}"); Console.WriteLine($"Width: {dimensions.GetWidth()}");
Viz také
- #B0 objektově orientované programování #C1
- Rozhraní
- Jak explicitně implementovat členy dvou rozhraní