有没有办法调用重写方法的父版本?(C#.NET) [英] Is there any way to call the parent version of an overridden method? (C# .NET)

查看:23
本文介绍了有没有办法调用重写方法的父版本?(C#.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我尝试了两种方法来访问methodTwo的父版本,但结果总是2.有没有什么方法可以在不修改这两个类的情况下从ChildClass实例中获得1结果?

In the code below I tried in two ways to access the parent version of methodTwo, but the result was always 2. Is there any way to get the 1 result from a ChildClass instance without modifying these two classes?

class ParentClass
{
    public int methodOne()
    {
        return methodTwo();
    }

    virtual public int methodTwo()
    {
        return 1;
    }
}

class ChildClass : ParentClass
{
    override public int methodTwo()
    {
        return 2;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var a = new ChildClass();
        Console.WriteLine("a.methodOne(): " + a.methodOne());
        Console.WriteLine("a.methodTwo(): " + a.methodTwo());
        Console.WriteLine("((ParentClass)a).methodTwo(): "
         + ((ParentClass)a).methodTwo());
        Console.ReadLine();
    }
}

更新 ChrisW 发布了这个:

Update ChrisW posted this:

在课外,我不知道任何简单的方法;但是,也许,我不知道如果你尝试会发生什么反射:使用 Type.GetMethod查找 MethodInfo 的方法与方法中的ParentClass,然后调用MethodInfo.Invoke

From outside the class, I don't know any easy way; but, perhaps, I don't know what happens if you try reflection: use the Type.GetMethod method to find the MethodInfo associated with the method in the ParentClass, and then call MethodInfo.Invoke

该答案已被删除.我想知道这个 hack 是否可行,只是出于好奇.

That answer was deleted. I'm wondering if that hack could work, just for curiosity.

推荐答案

在 IL 级别,您可能可以发出 call 而不是 callvirt,并获得工作完成 - 但如果我们将自己限制在 C# ;-p(编辑该死!运行时阻止你:VerificationException:操作可能会破坏运行时的稳定性.";删除 virtual 并且它工作正常;太聪明了一半......)

At the IL level, you could probably issue a call rather than a callvirt, and get the job done - but if we limit ourselves to C# ;-p (edit darn! the runtime stops you: VerificationException: "Operation could destabilize the runtime."; remove the virtual and it works fine; too clever by half...)

ChildClass 类型中,您可以使用 base.methodTwo() - 但是,这在外部是不可能的.你也不能下降超过一层 - 没有 base.base.Foo() 支持.

Inside the ChildClass type, you can use base.methodTwo() - however, this is not possible externally. Nor can you go down more than one level - there is no base.base.Foo() support.

但是,如果您使用方法隐藏禁用多态性,您可以获得您想要的答案,但原因很糟糕:

However, if you disable polymorphism using method-hiding, you can get the answer you want, but for bad reasons:

class ChildClass : ParentClass
{
    new public int methodTwo() // bad, do not do
    {
        return 2;
    }
}

现在您可以根据变量是定义为 ChildClass 还是 ParentClass 来从同一个对象中得到不同的答案.

Now you can get a different answer from the same object depending on whether the variable is defined as a ChildClass or a ParentClass.

这篇关于有没有办法调用重写方法的父版本?(C#.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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