不使用激活器从字符串创建类的实例 [英] create an instance of class from string without using activator

查看:70
本文介绍了不使用激活器从字符串创建类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<pre>

Hi,

I have the following code:
           <pre> switch (Common.Globals.Type)
            {
                case Common.Globals.eType.Car:
                    return new CarForYou(color);

                case Common.Globals.eType.Truck:
                    return new TruckFotYou(color);

                case Common.Globals.eType.Motorcycle:
                    return new MotorcycleFotYou(color);
                default:
                    throw new NotImplementedException();
            }</pre>

and I want to collapse this code.
the user choose the type and I want to use this string to create the instance,
how can I do something like the following (instead of the above code):

<pre>return new "UserChoose"+ForYou(color);</pre>

Thanks.



推荐答案

如果您不想切换,请 Activator。 CreateInstance [ ^ ]是你可以做到的唯一方法。

无法使用直接从字符串创建新实例新的类型缺点tructor syntax。
If you don't want the switch, then Activator.CreateInstance[^] is pretty much the only way you can do it.
There is no way to create a new instance directly from a string using the new type-constructor syntax.


在某种程度上,请求闻起来像滥用。如果你从字符串生成代码,它可能会变得不可维护,因为编译器无法检查字符串中的内容。



尽管如此,获取一些CIL的常规方法字符串中的代码是CodeDOM。

请看我过去的答案:

使用CodeDom生成代码 [ ^ ]。



如果要使用编译,可能遇到的主要问题是卸载生成的代码CodeDOM反复出现。这是因为卸载组件是不可能的。它只能在整个Application Domain中卸载,但是您需要在运行时创建的 AppDomain 中完成所有工作,并通过域边界使用此代码。反过来,意味着使用IPC(因为域是隔离的)。这一切都很可行,但却带来了相当大的复杂性。



我在其他答案中讨论了这种发展:创建使用Reloadable Plugins的WPF应用程序...... [ ^ ]。



-SA
To certain extent, the request smells like abuse. If you generate code from strings, it may turn non-maintainable, because a compiler cannot check up what's in your string.

Nevertheless, the regular way of obtaining some CIL code from strings is CodeDOM.
Please see my past answer:
code generating using CodeDom[^].

The major problem you may face is unloading of the generated code, if you want to compile using CodeDOM repeatedly. This is because it is impossible to unload an assembly. It can only be unloaded with the whole Application Domain, but then you would need to do all the job in an AppDomain created during runtime and work with this code through domain boundary, which, in turn, means using IPC (because domains are isolated). This is all doable, but presents a considerable complication.

I discussed this kind of development in my other answer: Create WPF Application that uses Reloadable Plugins...[^].

—SA


这篇关于不使用激活器从字符串创建类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆