相关疑难解决方法(0)

如何调用base.base.method()?

// Cannot change source code
class Base
{
    public virtual void Say()
    {
        Console.WriteLine("Called from Base.");
    }
}

// Cannot change source code
class Derived : Base
{
    public override void Say()
    {
        Console.WriteLine("Called from Derived.");
        base.Say();
    }
}

class SpecialDerived : Derived
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.Say();
    }
}

class Program
{
    static void Main(string[] args)
    {
        SpecialDerived sd = new SpecialDerived();
        sd.Say();
    }
}
Run Code Online (Sandbox Code Playgroud)

结果是:

来自Special Derived.
来自Derived./*这不是预期的*/
从Base调用.

如何重写SpecialDerived类,以便不调用中产阶级"Derived"的方法?

更新: 我想继承Derived而不是Base的原因是Derived类包含许多其他实现.既然我不能在 …

c# polymorphism

108
推荐指数
7
解决办法
9万
查看次数

有没有办法调用重写方法的父版本?(C#.NET)

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

更新 ChrisW发布了这个:

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

那个答案被删除了.我想知道这个黑客是否可行,只是为了好奇.

.net c# inheritance

37
推荐指数
3
解决办法
4万
查看次数

使用派生类对象访问基类方法

如果我正在使用阴影,并且如果我想使用派生类对象访问基类方法,我该如何访问它?

c#

7
推荐指数
3
解决办法
2万
查看次数

标签 统计

c# ×3

.net ×1

inheritance ×1

polymorphism ×1