简体   繁体   English

使用派生的 class 对象访问基本 class 方法

[英]Access the base class method with derived class objects

If I am using shadowing and if I want to access base class method with derived class objects, how can I access it?如果我正在使用阴影,并且我想使用派生的 class 对象访问基本 class 方法,我该如何访问它?

Use the base keyword:使用base关键字:

base.MethodOnBaseClass();

The base keyword is used to access members of the base class from within a derived class: base关键字用于从派生的 class 中访问基 class 的成员:

First cast the derived class object to base class type and if you call method it invokes base class method.首先将派生的 class object 转换为基础 class 类型,如果调用方法,它会调用基础 class 方法。 Keep in mind it works only when derived class method is shadowed.请记住,它仅在派生的 class 方法被隐藏时才有效。

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
    }
}

You qualify the method call:您限定方法调用:

base.foo();
DerivedClass derivedObj = new DerivedClass(); 
(derivedObj as BaseClass).Method1(); // cast to base class with method invoke

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM