Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two classes:

public class MyBase
{
    public virtual void DoMe()
    {

    }
}

public class MyDerived:MyBase
{
    public override void DoMe()
    {
        throw  new NotImplementedException();
    }
}

And I have the following code to instantiate MyDerived:

        MyDerived myDerived=new MyDerived();

The thing is how to call DoMe of the base class? If I use myDerived.DoMe(), then the derived method wil be called, resulting in an exception. I tried to cast myDerived to MyBase, yet it is still the derived version of the method that gets called.

Edit: As mentioned in the below comment, I can't change eitehr MyDerived or MyBase because they are not my code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
589 views
Welcome To Ask or Share your Answers For Others

1 Answer

There's a solution, but it's ugly: use reflection to get the base-class method, and then emit the IL necessary to call it. Check out this blog post which illustrates how to do this. I've successfully used this approach it to call the base class's implementation of a method when all I have is a reference to a derived class which overrides that method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...