繁体   English   中英

如何使用在子类中创建的方法(不是在接口上实现的方法) C#.NET

[英]How to use a method created in a child class (not those implemented on interface) | C# .NET

我正在玩C#中的接口并进行实验,我试图从接口继承以在子类中实现其方法,但是其中一个子类中,我添加了不在接口中的方法,但我无法调用它。

我该怎么办? 这就是我所拥有的

接口:

interface IShape
{
    double GetPerimeter();
    double GetArea();
}

类别:

public class Square : IShape
{
     public double  GetPerimeter()
     {
         // all code here
     }

     public double GetArea()
     {
         // all code here
     }
}

public class Rectangle : IShape
{
     public double  GetPerimeter()
     {
         // all code here
     }

     public double GetArea()
     {
         // all code here
     }

     public string PrintShape()
     {
         return "This is a rectangle!"
     }
}

主程序:

IShape shape = null;
Console.WriteLine("Select Shape");
Console.WriteLine("1- Rectangle");
Console.WriteLine("2- Square");
int shapeSelected = int.Parse(Console.ReadLine());

if (shapeSelected.Equals(1))
{
     shape = new Rectangle();
}
else
{
     shape = new Square();
}

如果我尝试从Rectangle类调用方法“ PrintShape”,则不允许这样做,如何使用不是来自接口的方法?

谢谢!

您在这里有一些误解,接口只是您的类必须实现的一堆方法。 您不继承接口,而是实现接口。

现在解决您的问题。 由于IShape不知道方法PrintShape,因此,如果您定义是否尝试调用shape.PrintShape() ,则由于我上面提到的原因,它将无法编译。

你怎么解决呢? 您有2个选择1是将您的形状像这样((Rectangle)shape).PrintShape()或我建议您实际执行的操作,将签名赋予接口,并在正方形中将其实现为空白

由于该方法特定于该对象,因此您必须将接口转换为该对象。

var text = ((Rectangle)shape).PrintShape();

如果要确保仅将其应用于矩形,请检查as是否为null。

var rectangle = shape as Rectangle;
if (rectangle != null)
    var text = rectangle.PrintShape();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM