Instantiate a class from its string name

Asked

Viewed 745 times

3

I have a select where I have some options

  • Teste1
  • Teste2
  • Teste3

I have a model for each option

public class Teste1() {
//atributos e métodos
} 

I would like to receive this string ex in a certain part of my system: "Teste1"

and create a Teste1 object

something like:

var objeto = new "Teste1"

That is to generate an object from its name

  • 1

    Are you sure you need this? In general you don’t need it, it has much better mechanisms. I could indicate something if I knew the problem you’re trying to solve. This is already common practice in dynamic language, even worse in static language. It is often done to save some typing and this is not appropriate. It would complicate the application without gain. On the contrary.

  • Of course please, the problem is that I will have an isValid method in each model, teste1, teste2 , and in a controller I need to receive from the view which face I want to validate, however in my view I only have how to pass the name of the class because it will come from the choice of the user there on the screen, then I would only worry about creating the instance from the choice of it, and call the isValid

1 answer

2


This can be done using Activator.CreateInstance.

Usually there is no real need to work with this, so it is good to analyze the problem well and rethink about the use of this mechanism.

The code would be like this:

var objeto = Activator.CreateInstance("Assembly", "Teste1");

Where Assembly is the name of Assembly where the class is. It is possible to use null if the Assembly whatever is being executed.

  • face am passing the Assembly (at least I think I am) and I burst an error when the file was not found, but in case it is in another project in the same solution the path of the class I want to instantiate is in Projectmain.Models.Testedomain so I’m passing like this var objeto = Activator.CreateInstance("ProjetoDomain.Models.TesteDomain", "Teste1");

  • Solved like this (using your example): string type = "Model"; var x = Assembly.Load("Assembly"). Gettypes(). First(t => t.Name == type); var y = Activator.Createinstance(x); y.Gettype(). Getmethod("Method"). Invoke(y, null);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.