C#显式地实现接口成员的方法
本文实例讲述了C#显式地实现接口成员的方法。分享给大家供大家参考。具体实现方法如下:
//explicit1.cs interfaceIDimensions { floatLength(); floatWidth(); } classBox:IDimensions { floatlengthInches; floatwidthInches; publicBox(floatlength,floatwidth) { lengthInches=length; widthInches=width; } //显式接口成员实现: floatIDimensions.Length() { returnlengthInches; } //显式接口成员实现: floatIDimensions.Width() { returnwidthInches; } publicstaticvoidMain() { //声明类实例“myBox”: BoxmyBox=newBox(30.0f,20.0f); //声明接口实例“myDimensions”: IDimensionsmyDimensions=(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 //声明英制单位接口: interfaceIEnglishDimensions { floatLength(); floatWidth(); } //声明公制单位接口: interfaceIMetricDimensions { floatLength(); floatWidth(); } //声明实现以下两个接口的“Box”类: //IEnglishDimensions和IMetricDimensions: classBox:IEnglishDimensions,IMetricDimensions { floatlengthInches; floatwidthInches; publicBox(floatlength,floatwidth) { lengthInches=length; widthInches=width; } //显式实现IEnglishDimensions的成员: floatIEnglishDimensions.Length() { returnlengthInches; } floatIEnglishDimensions.Width() { returnwidthInches; } //显式实现IMetricDimensions的成员: floatIMetricDimensions.Length() { returnlengthInches*2.54f; } floatIMetricDimensions.Width() { returnwidthInches*2.54f; } publicstaticvoidMain() { //声明类实例“myBox”: BoxmyBox=newBox(30.0f,20.0f); //声明英制单位接口的实例: IEnglishDimensionseDimensions=(IEnglishDimensions)myBox; //声明公制单位接口的实例: IMetricDimensionsmDimensions=(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#程序设计有所帮助。