代码之家  ›  专栏  ›  技术社区  ›  Protector one reece

访问不同类实例的同名类成员

  •  1
  • Protector one reece  · 技术社区  · 16 年前

    instance['Text'] = value;
    

    注意:不幸的是,这两个类都没有实现与文本成员相同的接口。

    4 回复  |  直到 16 年前
        1
  •  2
  •   Darin Dimitrov    16 年前

    与javascript不同,C#是一种静态语言,如果两个类都没有实现公共接口或基类,那么可以使用反射来实现相同的目标。

    instance.GetType().GetProperty("Text").SetValue(instance, "new value", null);
    
        2
  •  1
  •   Konamiman    16 年前

    reflection

    typeof(A).GetProperty("Text").GetValue(theInstance, null);
    

    哪里 theInstance 将是一个类的实例。

        3
  •  0
  •   user224564    16 年前

    尽量不要使用反射,因为你可以用其他方法来做同样的事情。

        4
  •  0
  •   irfn    16 年前

    如果你能让A和B实现相同的接口

     interface ISomeGenericNameForAAndB
    {
        string Text { get; }
    }
    class A :ISomeGenericNameForAAndB
    {
        public string Text { get { return "some Text from A"; } }    
    }
    class B : ISomeGenericNameForAAndB
    {
        public string Text { get { return "some Text from B"; } }
    }
    
    ISomeGenericNameForAAndB anAInstance = new A();
    ISomeGenericNameForAAndB aBInstance = new B();