gpt4 book ai didi

java - C# 从子类访问父类的方法

转载 作者:行者123 更新时间:2023-12-02 02:52:18 24 4
gpt4 key购买 nike

我正在尝试用 C# 编写一段与 Java 中已有的代码等效的代码。 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; }
}

这给出了输出 1 1 2 2。现在,我已经为 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;
}
}

但是,这会打印 1 1 2 1 ,因为 C2 中继承的 M2 调用 C1 中的 M1,而不是 C2 中的 M1。怎样才能让它在C2中调用M1并稍作修改?

最佳答案

注意:在 C# 中,您需要使用 virtualoverride 关键字来允许覆盖。 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.

(我的粗体)

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

关于java - C# 从子类访问父类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43613061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com