Execute method of one nested class as property in another in C #

1

I have the following class:

public class Feliz : IFeliz
{
   //public algumas propeiedades e tals... { get; set; }
   public bool EstaFeliz()
   {
      //Faz alguma coisa...
   }
}

And it's a property in another class:

public Exemplo
{
   public IFeliz Feliz { get; set; }
   // Outras propriedades e métodos etc...
}

Now inside my executable I'm creating an example instance by reflection. And I want to access the Feliz.EstaFeliz () method through it. Has as? I'm trying something like this:

Executor(string ClasseChamada) // onde ClasseChamada = "Exemplo"
{
   //Pega o objeto Exemplo blz! (já testado)
   Type ExemploType = Type.GetType(ClasseChamada + ",namespace") ;
   ConstructorInfo ExemploConstructor = ExemploType.GetConstructor(Type.EmptyTypes);
   object ExemploClassObject = ExemploConstructor.Invoke(new object[] { });

   //Tentativa de pegar a propriedade Feliz para chamar seu método...
   PropertyInfo FelizPropery = ExemploType.GetProperty("Feliz"); //PropertyInfo permitem chamar métodos?
   MethodInfo methodFeliz = FelizType.GetType().GetMethod("EstaFeliz");
   methodFeliz.Invoke(FelizPropery, null);
}

As you may have noticed, I'm kind of lost in this second part there ... could anyone save me?

    
asked by anonymous 07.11.2017 / 17:32

1 answer

1

AlamBique, basically the problem is that you are trying to invoke a method of an object that does not yet exist.

In your class definition Exemplo , you have a property of type IFeliz not yet assigned by any object, so there is no way you can invoke a method.

Assuming you have a string with the name of the class to be assigned to the property Feliz (if it is the same string , easier), you only need to create a new instance of that class and assign it the property. I usually do this:

Type tipo = Type.GetType("namespace." + nomeClasse);
var instancia = Activator.CreateInstance(tipo);
  

So far I just created the object to be assigned to the property of ExampleClassObject

FelizPropery.SetValue(ExemploClassObject, instancia);
  

That was the assignment. You now have the property Feliz , of the object of type Exemplo pointing to an object of type Feliz .

     

I followed his variable name FelizPropery ...

Apart from the fact that you do not need to do the assignment to invoke the method, you now have instancia on hand to invoke it, knowing that it is the same object that was assigned to the Feliz property of the object type Exemplo .

MethodInfo metodo = tipo.GetMethod("EstaFeliz");
bool resultado = (bool)metodo.Invoke(instancia, null);
    
07.11.2017 / 21:40