执行一个嵌套类的方法作为另一个嵌套类的属性

时间:2017-11-07 18:09:53

标签: c# .net system.reflection

我有以下课程:

public class Happy : IHappy
{
   //public some properties and etc... { get; set; }
   public bool IsHappy()
   {
      //Do something...
   }
}

它是另一个类中的属性:

public class Exemplo
{
   public IHappy Happy { get; set; }
   // Other properties and methods etc...
}

现在我的可执行文件中我正在通过反射创建一个示例实例。我想通过它访问Happy.IsHappy()方法。有可能的?我正在尝试这样的事情:

DoThiks(string CalledClass) // where CalledClass = "Exemplo"
{
   //Instantiate the object Exemplo (working fine)
   Type ExemploType = Type.GetType(CalledClass + ",namespace");
   ConstructorInfo ExemploConstructor = ExemploType.GetConstructor(Type.EmptyTypes);
   object ExemploClassObject = ExemploConstructor.Invoke(new object[] { });

   //Problem is here.
   //Try instantiate the Happy property to call his method...
   PropertyInfo HappyPropery = ExemploType.GetProperty("Happy"); //PropertyInfo can call methods?
   MethodInfo methodHappy = HappyPropery.GetType().GetMethod("IsHappy");
   methodHappy.Invoke(HappyPropery, null);
}

正如你可能已经注意到的那样,我在第二部分中迷失了......有人可以救我吗?

2 个答案:

答案 0 :(得分:1)

我想你需要

var methodHappy = HappyPropery.PropertyType.GetMethod("IsHappy");
var propertyValue = HappyPropery.GetValue(ExemploClassObject);
if (propertyValue != null)
  var isHappy = methodHappy.Invoke(propertyValue, new object[0]);

请参阅MSDN

答案 1 :(得分:0)

基本上,问题是您正在尝试调用尚不存在的对象的方法。 我是否需要分配Happy属性,或者无法调用方法。

void DoThiks(string CalledClass) // where CalledClass = "Exemplo"
    {

        Type ExemploType = Type.GetType("TestesWindowsForms.TesteReflexao.Exemplo");
        ConstructorInfo ExemploConstructor = ExemploType.GetConstructor(Type.EmptyTypes);
        object ExemploClassObject = ExemploConstructor.Invoke(new object[] { });


        //Solution here:
        //Creating the object to be assigned to the property of ExampleClassObject
        Type HappyType = Type.GetType("TestesWindowsForms.TesteReflexao.Happy");
        object HappyClassObject = Activator.CreateInstance(HappyType);

        PropertyInfo HappyPropery = ExemploType.GetProperty("Happy");
        HappyPropery.SetValue(ExemploClassObject, HappyClassObject);
        //That was the assignment. Now I have the Happy property of the type object pointing to an object of type Happy.

        MethodInfo EstaHappy = HappyType.GetMethod("IsHappy");
        bool Resultado = (bool)EstaHappy.Invoke(HappyClassObject, null);

        MessageBox.Show(Resultado.ToString());
    }