Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从字符串创建UserControl_C#_Wpf_User Controls - Fatal编程技术网

C# 如何从字符串创建UserControl

C# 如何从字符串创建UserControl,c#,wpf,user-controls,C#,Wpf,User Controls,有没有一种简洁的方法可以从字符串创建UserControl 我希望避免这样的硬编码: if (tool.ToolName == "Image_Tool") { ctl = new Image_Tool() as UserControl; } UserControl ctl = new tool.toolName() as UserControl Image_工具是一个现有的用户控件。ToolName是通过解析文件夹来获取UserControl文件名的 我很想做这样的事情: if (tool.

有没有一种简洁的方法可以从字符串创建UserControl

我希望避免这样的硬编码:

if (tool.ToolName == "Image_Tool") { ctl = new Image_Tool() as UserControl; }
UserControl ctl = new tool.toolName() as UserControl
Image_工具是一个现有的用户控件。ToolName是通过解析文件夹来获取UserControl文件名的

我很想做这样的事情:

if (tool.ToolName == "Image_Tool") { ctl = new Image_Tool() as UserControl; }
UserControl ctl = new tool.toolName() as UserControl
那是“天上的馅饼”吗?PHP有一种将字符串转换为变量的方法……想知道C#是否有这样的方法

谢谢

Hans,尝试了你的建议,但现在得到了此代码的TypeLoadException:

  ObjectHandle handle = Activator.CreateInstance("AutomationSystem", tool.ToolName);
            Object o = handle.Unwrap();
            ctl = o as UserControl;

这是一个windows应用程序,不是web应用程序,所以不存在dll,只有exe。

所以Hans是对的。我的命名空间位于错误的位置。我是这样解决的:

ObjectHandle handle = Activator.CreateInstance(null, "AutomationSystem.Toolbox."+tool.ToolName);
                Object o = handle.Unwrap();

                ctl = o as UserControl;

使用Activator.CreateInstance()。别忘了名称空间名称。Hans,我在web上尝试了Activator.CreateInstance的不同建议,但都没有用。我在上面所做的方式似乎应该可以工作,但我得到的信息是,在程序集中找不到Image_工具(尝试了null来代替“AutomationSystem”,它找到了当前程序集)。当我可以分配一个UserControl变量=new Image\u Tool()时,无法理解为什么找不到Image\u Tool。没有代码问题。。。有什么建议吗?请同事回头看看。非零概率的情况下,他会指着自己的手指大叫“老兄,你忘了名称空间的名字了”。