gpt4 book ai didi

c# - 基类的方法总是被调用

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:54 25 4
gpt4 key购买 nike

我有一个基类和一个派生类

public interface IDispatch {
void DoSomething();
}

public class Foo : IDispatch {
void DoSomething() {

}
}

public class Bar : Foo {
void DoSomething() {

}
}

我有一个函数,基于条件,我正在引用它。

  Foo randomfunc(Foo f){
if(...){
f = new Foo();
}else{
f = new Bar();
}
f.dosomething(); // this works fine
return f;

}

但是在方法调用中

Foo qwe;
qwe = randomfunc(f);
qwe.doSomething(); //it calls doSomething() from Foo() even though it references Bar

我哪里错了?

最佳答案

隐藏方法,而不是覆盖它们。事实上,您会收到针对您编写的代码的警告(假设您修复了编译器错误,因为您正在使用私有(private)方法实现接口(interface))。

这个:

public class Bar : Foo
{
public void DoSomething()
{

}
}

等同于:

public class Bar : Foo
{
public new void DoSomething()
{

}
}

但是,后者会阻止警告,因为它告诉编译器“我知道我在做什么”。

通过隐藏方法,这意味着 Bar 的实现只有在您调用它的对象被强制转换为 Bar 时才会被调用。这就是您在这里遇到的行为。您实际上想要做的是覆盖该方法,而不是隐藏它。例如:

public class Foo : IDispatch
{
public virtual void DoSomething()
{

}
}

public class Bar : Foo
{
public override void DoSomething()
{

}
}

关于c# - 基类的方法总是被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43510174/

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