gpt4 book ai didi

c# - C#中从基类调用重写的方法

转载 作者:IT王子 更新时间:2023-10-29 04:43:19 25 4
gpt4 key购买 nike

给定以下 C# 类定义和代码:


public class BaseClass
{
public virtual void MyMethod()
{
...do something...
}
}

public class A : BaseClass
{
public override void MyMethod()
{
...do something different...
}
}

public class B : BaseClass
{
public override void MyMethod()
{
...do something different...
}
}

public class AnotherObject
{
public AnotherObject(BaseClass someObject)
{
someObject.MyMethod(); //This calls the BaseClass method, unfortunately.
}
}

我想调用在 A 或 B 中实际找到的 MyMethod(),假设传入的对象实际上是 A 或 B 的实例,而不是在 基类。缺少做这样的事情:


public class AnotherObject
{
public AnotherObject(BaseClass someObject)
{
A temp1 = someObject as A;
if (A != null)
{
A.MyMethod();
}

B temp2 = someObject as B;
if (B != null)
{
B.MyMethod();
}
}
}

我该怎么做?

最佳答案

调用哪个方法是通过传递给 AnotherObject 构造函数的类型的多态性来确定的:

AnotherObject a = new AnotherObject(new A()); // invokes A.MyMethod() 
AnotherObject b = new AnotherObject(new B()); // invokes B.MyMethod()
AnotherObject c = new AnotherObject(new BaseClass()); //invokes BaseClass.MyMethod()

关于c# - C#中从基类调用重写的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2299367/

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