代码之家  ›  专栏  ›  技术社区  ›  rootpanthera

C#初学者:调用父回调方法而不是子回调方法

c#
  •  0
  • rootpanthera  · 技术社区  · 9 年前

    我有一个小问题(仍在学习面向对象编程)。我正在调用parent的“GoTo”方法,我希望在完成时通知该对象,但由于某些原因,调用了来自父类的回调方法,而不是子类的回调方法(即使我将子对象作为参数传递)。

    问题: 很明显,我遗漏了一些非常基本的东西,但我不确定是什么。我需要做什么才能调用孩子的“Imthere”方法,而不是调用家长?(转换到父方法中的特定子对象不适用,因为我想重用在不同子对象上剪下的相同代码)。

    public class Parent {
    
        public void GoTo(Parent movingObject) { 
    
            //Random code here.
    
            OnComplete(movingObject.Imthere);
    
        }
    
        protected void Imthere() { 
    
            //This gets called when some task is Completed!
    
            Log("Parent");
        }
    }
    
    
    public class Child : Parent
    {
    
    
    
        protected void Imthere()
        {
    
            //This SHOULD get's called when task is completed, but it's not.
    
            Log("Child");
        }
    }
    

    非常感谢。

    1 回复  |  直到 9 年前
        1
  •  5
  •   15ee8f99-57ff-4f92-890c-b56153    9 年前

    它需要是父级中的虚拟方法:

    public class Parent {
    
        //... snip
    
        protected virtual void Imthere() { 
            Log("Parent");
        }
    }
    

    孩子需要添加 override

    public class Child : Parent
    {
        protected override void Imthere()
        {
            Log("Child");
        }
    }
    

    如果不这样做,实际上就是在告诉编译器,当有人接受调用时 Imthere 方法通过引用 Parent (或者引用方法,就像你做的一样——相同的区别),你 只有永远 父母亲 方法的版本。这是有充分理由的默认行为:您的类可能具有复杂的内部结构,其中有几个方法相互调用。您不希望任何随机子类能够通过用其他代码替换部分代码来破坏它。

    这个 virtual 推翻