从调用父类的子方法 [英] Calling child class method from parent

查看:200
本文介绍了从调用父类的子方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能为a.doStuff()方法来打印B做东西,而无需编辑类?如果是的话,我会怎么做呢?

Is it possible for the a.doStuff() method to print "B did stuff" without editing the A class? If so, how would I do that?

class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = new B();

        a.doStuff();
        b.doStuff();

        Console.ReadLine();
    }
}

class A
{
    public void doStuff()
    {
        Console.WriteLine("A did stuff");
    }
}

class B : A
{
    public void doStuff()
    {
        Console.WriteLine("B did stuff");
    }
}



我改装蒸汽游戏,界面完全音频。而且我不希望反编译,并重新编译这一切,因为这将与蒸汽螺丝。我的程序通过XNA'注入'到界面完全音频。我可以使用update()和借鉴()由XNA方法mod一些事情。但它相当有限。我wan't覆盖的基础方法mod更多的东西(worldgen为例)。

I'm modding a steam game, Terraria. And I don't want to decompile and recompile it all because that will screw with steam. My program 'injects' into Terraria via XNA. I can use the update() and draw() methods from XNA to mod some things. But it's pretty limited. I wan't to override base methods to mod more things (worldgen for example).

推荐答案

是的,如果你声明 doStuff 虚拟 A 然后覆盖 b

Yes, if you declare doStuff as virtual in A and then override in B.

class A
{
    public virtual void doStuff()
    {
        Console.WriteLine("A did stuff");
    }
}

class B : A
{
    public override void doStuff()
    {
        Console.WriteLine("B did stuff");
    }
}

这篇关于从调用父类的子方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆