【问题标题】:Call method of the derived class through reflection. Possible or no?通过反射调用派生类的方法。可能与否?
【发布时间】:2009-11-19 10:28:48
【问题描述】:

我有以下类结构:

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 (); }

在 ClassThatUses 中,我需要调用(通过反射 - 强制)类 Bar 的 Prepare 方法。

我需要编写一个反射代码来调用 Bar 而不是 foo 的 Prepare 方法,而不是问号 (???)。

基本上应该是这样的:

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)

不知道是Bar,还是BarBar,还是BarBarBar。我需要找出分配字段的 REAL 类型,而不是输入它被强制转换的类型。

这有可能吗? 或者至少有可能在运行时找出 Foo 字段的真实类型?

附言我意识到,如果没有反思,它将被称为 - 没问题。这更像是一种理论。

更新:http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx 请注意,您不能使用基类中的 MethodInfo 对象来调用派生类中的重写方法,因为后期绑定无法解析重写。 这是否意味着问题无法解决?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    GetType 方法会在运行时为您提供Foo 的真实类型:

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

    在您编辑之后,如果您想为 ClassThatUses 的特定实例找到 Foo 的运行时类型,那么您需要使用 GetValue 来询问 @ 的 987654329@ 在那个实例上:

    ClassThatUses o = new ClassThatUses() { Foo = new Bar() };
    
    // Type fooType = o.Foo.GetType();
    Type fooType = o.GetType().GetProperty("Foo").GetValue(o, null).GetType();
    

    【讨论】:

    • 非常感谢!这就是我所需要的!
    【解决方案2】:
    typeof(Bar).GetMethod("Prepare").Invoke(foo, new object[] { });
    

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

    至少有可能找出 Foo 字段的真实类型 运行时间?

    是的,使用 foo.GetType()

    【讨论】:

    • 也许我应该更精确地指定它。不知道是Bar,还是BarBar,还是BarBarBar。我需要找出分配字段的真实类型,而不是输入它被强制转换为的类型。
    • GetType 将为您提供“真实”类型。
    • 是的,但是当我去 ClassThatUses.GetType.GetProperties() -> 然后尝试获取 Foo 时,它说它是 Foo 类型的,而不是 Bar。
    猜你喜欢
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多