Pergunta

public class Foo
{
    public string Test()
    {
        return GetName();
    }

    public string GetName()
    {
        return "Foo";
    }
}

public class Bar : Foo
{
    public new string GetName()
    {
        return "Bar";
    }
}


new Foo().Test(); // Foo

new Bar().Test(); // also Foo

I was trying to create a "wrapper" for Foo so that I could unit test the behaviour of Test() when GetName() produces unexpected values. I cannot directly influence the behaviour of GetName() in Foo as it is dependent on ASP.NET pipeline events.

I was hoping

new Bar().Test();

would return "Bar", but obviously I have misunderstood the inheritance model.

Is there any way of achieving what I need?

Foi útil?

Solução

GetName needs to be virtual in your Foo and overridden in your Bar class. Like this:

public class Foo 
{
     public string Test()     
     {         
         return GetName();
     }

     public virtual string GetName()
     {
         return "Foo";
     }
}

public class Bar : Foo 
{
     public override string GetName()
     {
         return "Bar";
     }
} 

Edit: but I now see from your new comment that changing Foo might not be an option for you.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top