使用字符串变量设置'Class = new '(Using a string variable to set a 'Class = new ')

编程入门 行业动态 更新时间:2024-10-27 10:31:53
使用字符串变量设置'Class = new '(Using a string variable to set a 'Class = new ')

我有三个多态类。 根据用户输入,该类应设置为该用户的输入。 因此子类由用户决定,并且应该为'class = new inputClass'。 代码片段如下所示:

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

它说PlayerOneStats = new Mage(); ,我希望Mage()成为用户输入。

我看过Activator,Assembly,使用Type,尝试转换为GenerateStats的父级,但没有任何效果。 我发现很多人说它有效,而且有一个链接说它不起作用。 有人可以帮我清楚一下吗? 非常感谢你!

I have a three polymorphed classes. Based on user input the class should be set to that user's input. So the child class is decided by a user, and should make for 'class = new inputClass'. The snippet of code looks like:

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 the Mage() to be the user input.

I've looked at Activator, Assembly, using Type, trying to cast over to the parent of GenerateStats, but nothing works. I've found many people saying it works, and one link that says it doesn't work. Can somebody please clear this up for me? Thank you very much!

最满意答案

什么是Mage的基类(以及用户可以选择的其他类)? 你应该能够做到这一点:

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

What is the base class of Mage (and the other classes a 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(); }

更多推荐

本文发布于:2023-07-07 09:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1061404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   变量   Class   set   variable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!