C# 使用派生类对象访问基类方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10104180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access the base class method with derived class objects
提问by 3692
If I am using shadowing and if I want to access base class method with derived class objects, how can I access it?
如果我正在使用阴影并且我想使用派生类对象访问基类方法,我该如何访问它?
采纳答案by 3692
First cast the derived class object to base class type and if you call method it invokes base class method. Keep in mind it works only when derived class method is shadowed.
首先将派生类对象转换为基类类型,如果您调用方法,它会调用基类方法。请记住,它仅在派生类方法被隐藏时才起作用。
For Example,
例如,
Observe the commented lines below:
观察下面的注释行:
public class BaseClass
{
public void Method1()
{
string a = "Base method";
}
}
public class DerivedClass : BaseClass
{
public new void Method1()
{
string a = "Derived Method";
}
}
public class TestApp
{
public static void main()
{
DerivedClass derivedObj = new DerivedClass();
BaseClass obj2 = (BaseClass)derivedObj; // cast to base class
obj2.Method1(); // invokes Baseclass method
}
}
回答by Luchian Grigore
You qualify the method call:
您限定方法调用:
base.foo();
回答by Oded
回答by Ganesh Pandey
DerivedClass derivedObj = new DerivedClass();
(derivedObj as BaseClass).Method1(); // cast to base class with method invoke

