访问基类通过c#中的派生类B对象的函数是否有任何方法可以访问A类By B类对象的函数(Sum)并获得输出10.
Class A
{
public int Sum(int i)
{
return i+3;
}
}
Class B:A
{
public int Sum(int i)
{
return i+4;
}
}
B objectB=new B();
int result=objectB.Sum(7);
output:11
Run Code Online (Sandbox Code Playgroud)
声明A变量而不是B,仍然使用B的构造函数.
A objectB = new B();
int result=objectB.Sum(7);
Run Code Online (Sandbox Code Playgroud)
这将使用A的方法.这是唯一的,因为该方法是阴影的,不会被覆盖.
您也将获得一个编译器警告你的方法Sum中B,你可能会想将它定义为public new int Sum(int i)发出信号,表明隐藏的目的.