簡體   English   中英

如何在c#中調用基本重載方法?

[英]How to call base overloaded method in c#?

我有以下類層次結構

class A
{
    public virtual string M()
    {
        return M(String.Empty);
    }

    public virtual string M(string s)
    {
        return M(s, false);
    }

    public virtual string M(string s, bool flag)
    {
        // Some base logic here
    }
}

class B:A
{
    public override string M(string s, bool flag)
    {
        string baseResult = base.M(s);

        // Derived class logic here
    }
}

B類可用於兩種情況:

1)

A b = new B();
string result = b.M();

2)

B b2 = new B();
string result2 = b2.M(someString, true);

這兩種情況都會因StackOverflowException而崩潰。 這是因為在BM內部調用的base.M(字符串s,bool標志)將再次調用BM(字符串s,bool標志)。

有什么好方法可以避免這種情況嗎?

我明白,如果我調用base.M(s,flag),一切都會起作用,但如果其他人開發了一個衍生類並訪問base.M(s)怎么辦? 我不想在這里留下StackOverflowException的可能性。

現在我的層次結構看起來像

class A
{
    public string M()
    {
        return M(String.Empty, false);
    }

    public virtual string M(string s, bool flag)
    {
        // Some base logic here
    }
}

class B:A
{
    public override string M(string s, bool flag)
    {
        string baseResult = base.M(s, flag);

        // Derived class logic here
    }
}

通常這里的技巧是擁有一個 virtual (通常是具有大多數參數的virtual ),這是您唯一一個垂直調用的virtual 其他可能是非虛擬的,只需使用適當的默認值調用“主”。

我會用這樣的東西:

class A
{
    public virtual string M(string s = "", bool flag = false)
    {
        // Some base logic here
    }
}

而不是有3個重載方法,這些方法最終都使用硬編碼參數調用相同的方法。

你不應該真的這樣做,但有時當你需要一個廉價的'hacky'解決方案時,你可以做到以下幾點:

public interface IFooBar
{
    void DoSomething(Object obj);
}

public class Foo
{
    public virtual void DoSomething(Object input)
    {
        this.DoSomething(input, false);
    }

    protected virtual void DoSomething(Object input, bool skipSomeBits)
    {
        //Does stuff for Foo and Bar
        if (!skipSomeBits)
        {
            //Does stuff that is specific to Foo but does not need to happen to Bar
        }
    }
}

public class Bar : Foo
{
    public override void DoSomething(object input)
    {
        base.DoSomething(input, true);
    }
}

或者(這個比上面更合適)你可以創建虛擬方法,對於子( Bar )是空的並且不調用base但是對於父( Foo )它做的事情:

public interface IFooBar
{
    void DoSomething(Object obj);
}

public class Foo
{
    public virtual void DoSomething(Object input)
    {
        //Does Foo and Bar stuff
        this.DoSomething2(input);
    }

    protected virtual void DoSomething2(Object input)
    {
        //Does Foo stuff
    }

}

public class Bar : Foo
{
    protected override void DoSomething2(Object input)
    {
        //Does not call base.DoSomething2() therefore does nothing or can do Bar stuff if needs be...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM