创建具有其字符串变量名的类的对象实例字符串、实例、对象、变量名

2023-09-03 03:19:46 作者:字里行间全是你

我不知道我问的东西是否有效,但我只是想知道,如果它的存在以及它是如何工作的。因此,这里是我的问题:

I don't know the thing I am asking is available or not but I just want to know if it exists and how it works. So here is my question:

我有我自己的2-3自定义模型类。例如,客户,   员工和产品。现在我有一个字符串类的名称。和基于   类的名字进来的字符串,我要创建的对象,   返回到视图。我怎么能做到这一点?

I have 2-3 custom model class of my own. For example, Customer, Employee and Product. Now I have class name in a string. and based on the class name coming in a string, I have to create its object and return to a VIEW. How could I achieve this?

我知道的if else 语句中的选择,但我想尝试一个更美好,动态的方式......

I know a option of IF ELSE statement but I want to try a better,"Dynamic" way...

推荐答案

有类名的字符串是不够的,能够创建它的实例。 作为事实上,你需要完整的命名空间包括类名来创建一个对象。

Having the class name in string is not enough to be able to create its instance. As a matter of fact you will need full namespace including class name to create an object.

假设你具备以下条件:

string className = "MyClass";
string namespaceName = "MyNamespace.MyInternalNamespace";

比你可以创建一个类的实例,类对象 MyNamespace.MyInternalNamespace.MyClass 通过以下任一方法:

Than you you can create an instance of that class, the object of class MyNamespace.MyInternalNamespace.MyClass using either of the following techniques:

var myObj = Activator.CreateInstance(namespaceName, className);

或者这样的:

or this:

var myObj = Activator.CreateInstance(Type.GetType(namespaceName + "." + className));

希望这会有所帮助,请让我知道如果没有。

Hope this helps, please let me know if not.