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");
}
}
Your current code is equivalent to:
public class A : IMy
{
public void F()
{
Console.WriteLine("A");
}
}
public class B : A
{
public new void F() // <--- Note 'new' here
{
Console.WriteLine("B");
}
}
You're implicitly marking the method as new, which will generate a compiler warning unless you explicitly write it.
What you actually want is to override the method, so declare that:
public class A : IMy
{
public virtual void F() // <--- Mark as virtual to allow subclasses to override
{
Console.WriteLine("A");
}
}
public class B : A
{
public override void F() // <-- Override the method rather than hiding it
{
Console.WriteLine("B");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.