简体   繁体   English

从C#中的子类访问父方法

[英]Access Parent's method from child class in C#

I am trying to make an equivalent code in C# for a piece of code that I already have in Java. 我试图用C#编写与Java中已经存在的代码等效的代码。 The Java code is as follows. Java代码如下。

class Test
{
        public static void main (String args[])
        {
            C1 o1 = new C1();
            C2 o2 = new C2();
            System.out.println(o1.m1() + " " + o1.m2() + " " + o2.m1() + " " + o2.m2());
        }

}

class C1 
{
    void C1() {}
    int m1() { return 1; }
    int m2() { return m1(); }
}

class C2 extends C1
{
    void C2() {}
    int m1() { return 2; }
}

This gives the output 1 1 2 2. Now, I have written this code for C#. 这给出了输出1 1 22。现在,我已经为C#编写了这段代码。

class Program
    {
        static void Main(string[] args)
        {
            C1 o1 = new C1();
            C2 o2 = new C2();
            Console.WriteLine(o1.M1()+ " "+ o1.M2()+ " "+ o2.M1()+ " "+ ((C2)o2).M2()+ "\n");
            Console.ReadKey();
        }
    }

    public class C1
    {
        public C1()
        {
        }
        public int M1()
        {
            return 1;
        }
        public int M2()
        {
            return M1();

        }
    }

    public class C2:C1
    {
        public C2()
        {             
        }
        public int M1()
        {
            return 2;
        }
    }

This, however, prints 1 1 2 1 as the inherited M2 in C2 calls the M1 in C1 and not the M1 in C2. 但是,这会打印1 1 2 1, 因为C2中继承的M2称为C1中的M1,而不是C2中的M1。 How can I make it call M1 in C2 with minor modifications? 经过细微的修改后,如何在C2中将其称为M1?

Note: in C# you need to use virtual and override keywords to allow overriding. 注意:在C#中,您需要使用virtualoverride关键字来允许覆盖。 MSDN : MSDN

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class . virtual关键字用于修改方法,属性,索引器或事件声明, 并允许在派生类中覆盖它

(my bolding) (我的粗体)

 class Program
    {
        static void Main(string[] args)
        {
            C1 o1 = new C1();
            C2 o2 = new C2();
            Console.WriteLine(o1.M1() + " " + o1.M2() + " " + o2.M1() + " " + ((C2)o2).M2() + "\n");
            Console.ReadKey();
        }
    }

    public class C1
    {
        public C1()
        {
        }
        public virtual int M1()
        {
            return 1;
        }
        public  int M2()
        {
            return M1();

        }
    }

    public class C2 : C1
    {
        public C2()
        {
        }
        public override int M1()
        {
            return 2;
        }
    }

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

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