I'm trying to create a method that takes a string and returns an instance of the class with the last name, eg "Calculator", will return me an instance of class "Calculator" time to determine which type it returns, because from what I researched I need to pass the type pro method as well. I tried: Type Tipo = Type.GetType("NomeDaClasse");
and then passing var x = RetornaClasse<Tipo>("Calculadora");
but to no avail. (Actually, I can not even decide the method to try.
static T RetornaClasse<T>(string nome) where T : class
{
return (T)Assembly.GetExecutingAssembly().CreateInstance(nome);
}
Usage: The return of this method will be parameter for this Generic Class:
public class Generico<T> where T : class
{
public T Objeto { get; set; }
public string ListarAtributos()
{
var p = Objeto.GetType().GetProperties();
string atributos = String.Empty;
foreach (PropertyInfo pop in p) // Lista de atributos
atributos += (String.Concat("[", pop.Name, "] = [", pop.GetValue(Objeto, null), "]\n"));
return atributos;
}
public string[] ListarMetodos()
{
var m = Objeto.GetType().GetMethods();
string[] metodos = new string[m.Length];
for (int i = 0; i < m.Length; i++)
metodos[i] = String.Concat(i, " [+] ", m[i].Name, "\n");
return metodos;
}
// TODO: Setar atributos, usar métodos
}
Solution:
static object RetornaClasse(string nome)
{
var classe = Assembly.GetExecutingAssembly().GetTypes().First(x => x.Name == nome);
var instancia = Activator.CreateInstance(classe);
return instancia;
}