Call method of the derived class through reflectio

2019-07-26 06:38发布

I have a follwing class structure:

public abstract class AbstractFoo
{
    public virtual void Prepare()
    {
    }
}
public class Foo : AbstractFoo
{
    public override void Prepare()
    {
    }
}

public class Bar : Foo
{
    public override void Prepare()
    {
    }
}

public class ClassThatUses
{
    public Foo Foo;
}

var classThatUsesInstance = new ClassThatUses { Foo = new Bar (); }

Somehow in ClassThatUses i need to call (through the reflection - mandatory) Prepare method of the class Bar.

Instead of question (???) marks i need to make a reflection code that will call the Prepare method of Bar rather than foo.

Basically, it should be something like:

classThatUsesInstance.GetType.GetProperties()[0] 
-> somehow understand that it's actually Bar, but not Foo. 
-> call method (which i know how to do, i just need the RIGHT method to be used)

I don't know whether it's Bar, or BarBar, or BarBarBar. I need to find out the REAL type of assigned field rather then type it was casted to.

Is this any possible? Or is it at least possible to find out the real type of the Foo field in runtime?

p.s. i realize that without reflection it will be called - no problem. this is more of a theory.

UPD: http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx Note that you cannot use the MethodInfo object from the base class to invoke the overridden method in the derived class, because late binding cannot resolve overrides. Does that mean the problem is unsolvable?

标签: c# reflection
2条回答
一纸荒年 Trace。
2楼-- · 2019-07-26 07:15

The GetType method will give you the real type of Foo at runtime:

public class ClassThatUses
{
    public Foo Foo { get; set; }

    public void CallPrepare()
    {
        // Foo.Prepare();
        Foo.GetType().GetMethod("Prepare").Invoke(Foo, null);
    }
}

Following your edit, if you want to find the runtime type of Foo for a particular instance of ClassThatUses then you'll need to use GetValue to interrogate the value of Foo on that instance:

ClassThatUses o = new ClassThatUses() { Foo = new Bar() };

// Type fooType = o.Foo.GetType();
Type fooType = o.GetType().GetProperty("Foo").GetValue(o, null).GetType();
查看更多
姐就是有狂的资本
3楼-- · 2019-07-26 07:25
typeof(Bar).GetMethod("Prepare").Invoke(foo, new object[] { });

or

foo.GetType().GetMethod("Prepare").Invoke(foo, new object[] { });

is it at least possible to find out the real type of the Foo field in runtime?

Yes, with foo.GetType()

查看更多
登录 后发表回答