Call method of the derived class through reflection. Possible or no?
I have a follwing class structure:
public abstract class AbstractF开发者_开发技巧oo
{
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?
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();
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()
精彩评论