简体   繁体   中英

Calling base class functions in C#.net

public class c2
    {
        public void Print()
        {
            MessageBox.Show("C2");
        }//print
    }//c2

    public class c1 : c2
    {
        public void Print()
        {
            MessageBox.Show("C1");
        }//print
    }//c1

How do i call Print() of base class(c2) using derived class Object(Function name are same in both classes)

您可以使用base.Print()来调用它。

If you have an instance of c1 , you can cast it to c2 to be able to call that method. For example:

var myc1 = new c1();

((c2)myc1).Print();

NOTE: This solution works in this example because c1.Print() only hides c2.Print() as opposed to overriding it.

public class c2 
{ 
    virtual public void Print() 
    { 
        MessageBox.Show("C2"); 
    }//print 
}//c2 

public class c1 : c2 
{ 
    override public void Print() 
    { 
        MessageBox.Show("C1"); 
        base.Print();
    }//print 
}//c1 

if you want run at C1's Print C2'S function, too. But to override the function the print function you shall declared it abstract or virtual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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