1

我正在学习如何在 C# 中正确应用 OO 原则。我遇到了一个小问题,我不知道如何解决它。我遇到以下问题:

目前的情况:

public abstract class Foo
{
    protected Foo()
    {
        //does nothing
    }
}

public class Bar : Foo
{
    public BarX ( int a, int b, int c) : base()
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public doStuff()
    {
        //does stuff
    }
}

public class BarY : Foo
{
    public Bar( int a, int b, int c) : base()
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public doStuff()
    {
        //does stuff
    }
}

关键是我有不同类型的Foo. 在这种情况下,它将是圆形和矩形。我希望它们具有相同的构造函数,因为每种类型都具有相同的属性。他们只有不同的doStuff()方法。我尝试了很多组合,但每次我尝试将参数移动到基类的构造函数时,它都会告诉我“某些类不包含带 0 个参数的构造函数”(或 3 个参数),具体取决于我在代码中的移动方式。

我的问题是如何将 a、b 和 c 的值分配给抽象类的构造函数?

4

2 回答 2

1

以下将起作用:

public abstract class Foo
{
    protected Foo(int a, int b, int c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public abstract void doStuff();
}

public class Bar : Foo
{
    public Bar(int a, int b, int c) : base(a, b, c)
    {
    }

    public override void doStuff()
    {
        //does stuff
    }
}


public class BarY : Foo
{
    public BarY(int a, int b, int c) : base(a, b, c)
    {
    }

    public override void doStuff()
    {
        //does stuff
    }
}
于 2012-12-10T14:00:46.837 回答
1

那是因为当你只有一个参数化的构造函数时BarY,并且BarX正在调用一个默认构造函数 ( base()),它在你的基类中不存在。您还需要通过 ( base(a, b, c)) 传递参数:

public abstract class Foo
{
    protected Foo(int a, int b, int c) 
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public abstract void doStuff();
}

public class Bar : Foo
{
    public BarX (int a, int b, int c) : base(a, b, c)
    {

    }

    public override void doStuff()
    {
        //does stuff
    }
}

public class BarY : Foo
{
    public Bar(int a, int b, int c) : base(a, b, c)
    {

    }

    public override void doStuff()
    {
        //does stuff
    }
}
于 2012-12-10T14:01:38.560 回答