我有以下代码
public interface IFoo
{
void Bar();
}
public class Parent : IFoo
{
public virtual void Bar(){}
}
public class Child : Parent, IFoo
{
public override void Bar(){}
}
IFoo test = new Child();
test.Bar();
test.Bar()
总是调用父方法
任何帮助将不胜感激
只有在明确实现后才应该发生。
我刚刚测试过,它可以工作。
代码正确。
public interface IFoo
{
string Bar();
}
public class Parent : IFoo
{
public virtual string Bar()
{
return "Hello world";
}
}
public class Child : Parent, IFoo
{
public override string Bar()
{
return "Hello world after override";
}
}
static void Main(string[] args)
{
IFoo test = new Child();
Console.WriteLine(test.Bar());
Console.ReadLine();
}
输出为:
Hello world after override
WorksForMe:问题一定在其他地方,当我运行此代码时,我看到正确地调用了子方法。要编译您的代码,我必须从接口中的方法中删除“ public”,然后给两个Bar()方法赋予一个主体。
C#4.0说语法有错误
public interface IFoo
{
void Bar();
}