开发者

Force to call virtual base function instead of the overriden one

In the开发者_如何学编程 following example "Test that v1 function was called" fails. Is there a way to force call the base implementation of "RunFunction" through an instance of "class V2" ?

    class V1 
    {
        public virtual string RunFunction()
        {
            return "V1";
        }
    }

    class V2 : V1
    {
        public override string RunFunction()
        {
            return "V2";
        }
    }



    [Test]
    public void TestCall()
    {
        var v1 = (V1)new V2();
        var v2 = new V2();

        Assert.IsTrue(v1.RunFunction() == "V1", "Test that v1 function was called");
        Assert.IsTrue(v2.RunFunction() == "V2", "Test that v2 function was called");
    }

Thanks for looking, guys and gals.


The whole point of class inheritance is that it allows you to override selected base class behavior.

You can use the base keyword from within V2 to call into base-class code from V1, but you cannot do that outside of the class. Just as a quick example of usage:

class V2 : V1
{
    public override string RunFunction()
    {
        return base.RunFunction();
    }
}

Alternatively you could instantiate an instance of V1:

var v1 = new V1();


I think you might get away with public new string RunFunction() in the subclass, but I'd also suggest that if V2 isn't supposed to provide it's own specific behaviour, then using inheritance isn't the right approach.

You could also try defining a static on the base -- public static string RunFuctionStatic(V1 item), then called as V1.RunFunctionStatic(v2Instace).


You could accomplish what you want with Reflection.

However, while it is unclear to me what your ultimate goal is, it is clear to me that you don't actually want to do what you're asking for. I suggest you spend some time re-educating yourself on polymorphism, and object oriented programming.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜