C Explicitly Implements Methods for Interface Members
- 2021-07-03 00:46:57
- OfStack
This article illustrates how C # explicitly implements interface members. Share it for your reference. The specific implementation method is as follows:
// explicit1.cs
interface IDimensions
{
float Length();
float Width();
}
class Box : IDimensions
{
float lengthInches;
float widthInches;
public Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
// Explicit interface member implementation:
float IDimensions.Length()
{
return lengthInches;
}
// Explicit interface member implementation:
float IDimensions.Width()
{
return widthInches;
}
public static void Main()
{
// Declare class instances " myBox ":
Box myBox = new Box(30.0f, 20.0f);
// Declare an interface instance " myDimensions ":
IDimensions myDimensions = (IDimensions) myBox;
// Print out the size of the box:
/* The following comment lines produce a compilation
Error, because these lines attempt to access the explicitly implemented
Interface members: */
//System.Console.WriteLine("Length: {0}", myBox.Length());
//System.Console.WriteLine("Width: {0}", myBox.Width());
/* Invoke a method from an instance of an interface,
To print out the size of the box: */
System.Console.WriteLine("Length: {0}", myDimensions.Length());
System.Console.WriteLine("Width: {0}", myDimensions.Width());
}
}
Code 2:
// explicit2.cs
// Declare the English unit interface:
interface IEnglishDimensions
{
float Length();
float Width();
}
// Declare the metric unit interface:
interface IMetricDimensions
{
float Length();
float Width();
}
// Object that implements the following two interfaces Box "Category:
// IEnglishDimensions And IMetricDimensions :
class Box : IEnglishDimensions, IMetricDimensions
{
float lengthInches;
float widthInches;
public Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
// Explicit implementation IEnglishDimensions Members of:
float IEnglishDimensions.Length()
{
return lengthInches;
}
float IEnglishDimensions.Width()
{
return widthInches;
}
// Explicit implementation IMetricDimensions Members of:
float IMetricDimensions.Length()
{
return lengthInches * 2.54f;
}
float IMetricDimensions.Width()
{
return widthInches * 2.54f;
}
public static void Main()
{
// Declare class instances " myBox ":
Box myBox = new Box(30.0f, 20.0f);
// Declare an instance of an English unit interface:
IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;
// Declare an instance of the metric unit interface:
IMetricDimensions mDimensions = (IMetricDimensions) myBox;
// Print dimensions in English units:
System.Console.WriteLine("Length(in): {0}", eDimensions.Length());
System.Console.WriteLine("Width (in): {0}", eDimensions.Width());
// Print dimensions in metric units:
System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
}
}
I hope this article is helpful to everyone's C # programming.