C#显式地实现接口成员的方法

时间:2021-05-20

本文实例讲述了C#显式地实现接口成员的方法。分享给大家供大家参考。具体实现方法如下:

// explicit1.csinterface IDimensions { float Length(); float Width();}class Box : IDimensions { float lengthInches; float widthInches; public Box(float length, float width) { lengthInches = length; widthInches = width; } // 显式接口成员实现: float IDimensions.Length() { return lengthInches; } // 显式接口成员实现: float IDimensions.Width() { return widthInches; } public static void Main() { // 声明类实例“myBox”: Box myBox = new Box(30.0f, 20.0f); // 声明接口实例“myDimensions”: IDimensions myDimensions = (IDimensions) myBox; // 打印出盒子的尺寸: //System.Console.WriteLine("Length: {0}", myBox.Length()); //System.Console.WriteLine("Width: {0}", myBox.Width()); System.Console.WriteLine("Length: {0}", myDimensions.Length()); System.Console.WriteLine("Width: {0}", myDimensions.Width()); }}

代码2:

// explicit2.cs// 声明英制单位接口:interface IEnglishDimensions{ float Length(); float Width();}// 声明公制单位接口:interface IMetricDimensions{ float Length(); float Width();}// 声明实现以下两个接口的“Box”类:// IEnglishDimensions 和 IMetricDimensions:class Box : IEnglishDimensions, IMetricDimensions{ float lengthInches; float widthInches; public Box(float length, float width) { lengthInches = length; widthInches = width; }// 显式实现 IEnglishDimensions 的成员: float IEnglishDimensions.Length() { return lengthInches; } float IEnglishDimensions.Width() { return widthInches; }// 显式实现 IMetricDimensions 的成员: float IMetricDimensions.Length() { return lengthInches * 2.54f; } float IMetricDimensions.Width() { return widthInches * 2.54f; } public static void Main() { // 声明类实例“myBox”: Box myBox = new Box(30.0f, 20.0f); // 声明英制单位接口的实例: IEnglishDimensions eDimensions = (IEnglishDimensions) myBox; // 声明公制单位接口的实例: IMetricDimensions mDimensions = (IMetricDimensions) myBox; // 以英制单位打印尺寸: System.Console.WriteLine("Length(in): {0}", eDimensions.Length()); System.Console.WriteLine("Width (in): {0}", eDimensions.Width()); // 以公制单位打印尺寸: System.Console.WriteLine("Length(cm): {0}", mDimensions.Length()); System.Console.WriteLine("Width (cm): {0}", mDimensions.Width()); }}

希望本文所述对大家的C#程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章