有什么办法来调用一个覆盖方法的父版本? (C#.NET) [英] Is there any way to call the parent version of an overridden method? (C# .NET)

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

问题描述

在code下面我试图访问methodTwo的父版本两种方式,但结果总是2.有没有办法从ChildClass实例得到1的结果,而无需修改这两个类<? / p>

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登载:

从类之外,我不知道
  没有简单的方法;但是,也许,我不
  知道,如果你尝试会发生什么
  反思:使用Type.GetMethod
  方法查找的MethodInfo
  与该方法相关联的
  父类,然后调用
  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

这答案被删除。我想知道如果黑客可以工作,只是出于好奇。

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

推荐答案

在IL层面,你很可能发出呼叫而非 callvirt ,并把工作做好 - 但如果我们把自己限制到C#;-p(修改混账运行时将停止你:<!code> VerificationException :操作可能会破坏运行时;删除虚拟,它工作正常;聪明过头了......)

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 父类

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天全站免登陆