class2的继承变量与class1(C#)不同

时间:2015-02-12 11:29:24

标签: c# inheritance

我刚刚创作了一个Shapes类和另外两个类(' Triangle'&' Square')继承了Shapes'。

public class Shapes
{
    private int sides;
}

public class Triangle : Shapes
{
    public void init()
    {
        int sides = 3;
        throw new System.NotImplementedException();
    }
}

public class Square : Shapes
{
    public void init()
    {
        int sides = 4;
        throw new System.NotImplementedException();
    }
}

代码是使用Classdiagram

设计的

问题:我应该如何调用该类,以便显示形状有多少边?

由于

2 个答案:

答案 0 :(得分:2)

您需要一个受保护的成员边,在每个形状的init-section中使用:

public class Shapes
{
    protected readonly int sides;
    public int NumberOfSides { get { return sides; } } 
}

public class Triangle : Shapes
{
    public Triangle()
    {
        this.sides = 3;
    }
}

public class Square : Shapes
{
    public Square()
    {
        this.sides = 4;
    }
}

正如Farhad Jabiyev提到的那样使用构造函数是初始化新实例的常用方法(参见上面的代码)

现在,当您拨打Shape#NumberOfSides时,Triangle获得3分,Square获得4分:

Shape square = new Square();
int number = square.NumberOfSides();

答案 1 :(得分:0)

您需要在具有此类访问者的类

上添加属性
public class Shapes
{
    private int sides;

    public int NumberOfSides { get { return sides; } } 
}

然后你可以去mySquare.NumberOfSides