How to use the text stored in one variable as the identifier of another variable [closed]

0

There is some function that I can use to tell the program that the text within a variable is a reference to an object that I want to instantiate so that it looks for that object using that text as an identifier of it

The language I'm using is C # (with windows form VS)

    
asked by Héctor Morales Veloz 19.08.2017 в 05:28
source

2 answers

1

With Type.GetType(string typeName) and Activator.CreateInstance(Type type) you can achieve it:

string className = "MiProyecto.Modelos.Persona";
Type classType = Type.GetType(className);
Persona persona = (Persona)Activator.CreateInstance(classType);
persona.Nombre = "Einer";

Here is a step by step.

First we save the name of the complete class with everything and namespace:

namespace MiProyecto.Modelos
{
  public class Persona
  {
     public int Id { get; set;}
     public string Nombre { get; set;}
  }
}

Then in the variable we would have:

string className = "MiProyecto.Modelos.Persona";

Now we need the System.Type of the class to be able to initialize it and we get it with Type.GetType() :

Type classType = Type.GetType(className);

As we already have the information of the class, we can initialize it with Activator.CreateInstance() :

Persona persona = (Persona)Activator.CreateInstance(classType);
persona.Nombre = "Einer";
    
answered by 19.08.2017 в 14:35
0

Good morning

Hoping to have understood your approach, I told you that I've used CreateIntance of the Activator class to instantiate objects knowing the data type; for which I consider for your case that you should also support Type for the string get the data type with GetType .

As such, CreateInstance of Activator has methods that allow you to directly create from strings but require two strings; I have not used them; but if you receive as parameter Type , bear in mind that to use it, your class must have a constructor without parameters.

Greetings.

    
answered by 19.08.2017 в 07:11