0

私は次のコードを持っています:

class ClassA
{
    public virtual void DoSomething()
    {
        DoSomething(1); // when called from ClassB, it calls DoSomething from ClassA with an infinite recursion
    }

    public virtual void DoSomething(int someInt)
    {
        // do something
    }
}

class ClassB : ClassA
{
    public override void DoSomething()
    {
        DoSomething(1);
    }
    public override void DoSomething(int someInt)
    {
         base.DoSomething(someInt);

        // do something
    }
}

class Program
{
    void someMethod()
    {
        ClassB instance = new ClassB();
        instance.DoSomething(); // stack overflow caused by infinite recursion
    }
}

私の問題は、呼び出すときにClassB.DoSomething();base.DoSomething(someInt);ClassBが派生する親クラスが、オーバーライドされたメソッドではなく、ClassAのメソッドを呼び出すようにしたいということです。

繰り返されるコードをコピー/貼り付けせずに、これをクリーンな方法で行う方法はありますか?

4

2 に答える 2

2

次のように基本クラスを変更できます。

class ClassA
{
    public virtual void DoSomething()
    {
        DoSomethingHelper(1); // when called from ClassB, it calls DoSomething from ClassA with an infinite recursion
    }

    public virtual void DoSomething(int someInt)
    {
        DoSomethingHelper(someInt);
    }

    private void DoSomethingHelper(int someInt)
    {
        // do something
    }
}

メソッド全体をプライベート メソッドにリファクタリングすることで、子クラスがアクセスする仮想メソッドを提供しながら、メソッドの現在のクラスの定義を呼び出す手段を提供します。

于 2012-12-05T22:09:33.187 に答える
0

仮想メソッドをオーバーライドすると、baseキーワードなしで呼び出すことができないため、そのクラスからの場合はcalできません。Jon Bが言ったことを試して、オーバーライドする代わりにメソッドシャドウイングを使用することができます。

class ClassA
{
    public void DoSomething()
    {
        DoSomething(1); 
    }

    public void DoSomething(int someInt)
    {
        Console.WriteLine("a");
    }
}

class ClassB : ClassA
{
    public new void DoSomething()
    {
        DoSomething(1);
    }

    public new void DoSomething(int someInt)
    {
        base.DoSomething();
    }
}
于 2012-12-05T21:08:41.463 に答える