我有2个班级
public class A
{
public A(string N)
{
Name = N;
}
public string Name { get; set; }
public void GetName()
{
Console.Write(Name);
}
}
public class B : A
{
public B(string N) : base(N)
{
}
public new void GetName()
{
Console.Write(new string(Name.Reverse().ToArray()));
}
}
我创建了一个新对象B
,我想从GetName
A
和GetName
B
来呼叫B foo = new B("foo");
foo.GetName(); // output "oof"
"foooof"
预期输出public new void GetName() : base
我已经尝试了AJAX
但是没有编译
答案 0 :(得分:2)
使用override并从重写方法调用基类'方法:
public class A
{
public virtual void GetName()
{
Console.Write(Name);
}
}
public class B : A
{
public override void GetName()
{
base.GetName();
Console.Write(new string(Name.Reverse().ToArray()));
}
}
virtual
关键字用于修改方法并允许在派生类中重写它,而new
修饰符隐藏基类方法。通过调用base.GetName();
您正在执行基本方法BTW,这就是为什么您在此处使用new
或override
关键字没有区别,尽管我建议使用override
参考文献:
答案 1 :(得分:2)
要获得所需的输出,您需要在base GetName()
的{{1}}方法中调用GetName()
方法。像这样举例如:
Class B
这将放出public class A
{
public A(string N)
{
Name = N;
}
public string Name { get; set; }
public void GetName()
{
Console.Write(Name);
}
}
public class B : A
{
public B(string N) : base(N)
{
}
public new void GetName()
{
base.GetName();
Console.Write(new string(Name.Reverse().ToArray()));
}
}
答案 2 :(得分:0)
public class A
{
public A(string N)
{
Name = N;
}
public string Name { get; set; }
public virtual void GetName()
{
Console.Write(Name);
}
}
public class B : A
{
public B(string N) : base(N)
{
}
public override void GetName()
{
base.GetName();
Console.Write(new string(Name.Reverse().ToArray()));
}
}
根据您的选择使用覆盖或新建。 喜欢处理这些场景。
A foo = new B("foo");
foo.GetName();
或
A foo = new A("foo");
foo.GetName();
或
B foo = new B("foo");
foo.GetName();
这msdn link会给你清晰的图片。