创建名称在字符串变量中的类的对象实例 [英] Create object instance of a class having its name in string variable

查看:15
本文介绍了创建名称在字符串变量中的类的对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我要问的东西是否可用,但我只想知道它是否存在以及它是如何工作的.所以这是我的问题:

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);

或者这个:

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

希望有帮助,如果没有,请告诉我.

Hope this helps, please let me know if not.

这篇关于创建名称在字符串变量中的类的对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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