Using a string variable to set 'class = new <string of class ()>'

I have three polymorphic classes. Based on user input, the class must be set to this user input. Thus, the child class is user-defined and must do for "class = new inputClass". The code for the fragment looks like this:

public void characterGeneration(string classSelected) { foreach (string classInList in classes.ClassList) { if (classSelected == classInList) { PlayerOneStats = new Mage(); } } PlayerOneStats.generateStats(); } 

Where it says PlayerOneStats = new Mage(); I want Mage() be a user.

I looked at Activator, Assembly using Type, trying to pass it to the parent element of GenerateStats , but nothing works. I found a lot of people saying this works, and one link that says it does not work. Can someone please clean this for me? Thank you very much!

+4
source share
3 answers

What is the base class of Mage (and other classes that the user can select)? You should be able to do this:

  public void characterGeneration(string classSelected) { foreach (string classInList in classes.ClassList) { if (classSelected == classInList) { PlayerOneStats = (GenerateStats)Assembly.GetExecutingAssembly().CreateInstance("YourNamespace." + classSelected); break; } } PlayerOneStats.generateStats(); } 
+1
source

Are you sure that the Activator is not working? Activator.CreateInstace("assembly-name", "type-name") seems to be exactly what you want. What does not work?

+3
source

Make sure you include the namespace in which you want, and this should work for you:

 string classSelected = "testCode.Mage"; var player = Activator.CreateInstance(Type.GetType(classSelected)); 

Since Activator.CreateInstance() returns an object that you will need to use - in your case it would be wise to apply to an interface that is implemented by all your classes of players:

 var player = (IPlayerCharacter) Activator.CreateInstance(Type.GetType(classSelected)); 
+1
source

Source: https://habr.com/ru/post/1383525/


All Articles