I've got the code below, I use class "B" to inherit class "A" while I wish to implement F function from interface IMy. But compiler tells my I'm hiding interface method "F". So the running result is "A".
I expect this program to output "B". I don't wish to use implicit interface implementation as I wish to use normal polymorphism in main function.
How to correct my code? Thanks.
public interface IMy
{
void F();
}
public class A : IMy
{
public void F()
{
Console.WriteLine("A");
}
}
public class B : A
{
public void F()
{
Console.WriteLine("B");
}
}
class Program
{
static void Main(string[] args)
{
IMy my = new B();
my.F();
}
}
To override a method in C#, the method in base class needs to be explicitly marked as virtual
. It doesn't matter if the method implements an interface method or not.
public class A : IMy
{
public virtual void F()
{
Console.WriteLine("A");
}
}
public class B : A
{
public override void F()
{
Console.WriteLine("B");
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments