将字符串转换为一个类名 [英] Converting a string to a class name

查看:303
本文介绍了将字符串转换为一个类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重新presents自定义类的名称的字符串变量。例如:

I have a string variable that represents the name of a custom class. Example:

string s = "Customer";

我需要为客户创造一个ArrayList。因此,所需要的语法是:

I will need to create an arraylist of customers. So, the syntax needed is:

List<Customer> cust = new .. 

如何转换字符串s能够创建此ArrayList上运行?

How do I convert the string s to be able to create this arraylist on runtime?

推荐答案

那么,对于一件事的ArrayList 不是一般的...你的意思是名单,其中,客户&GT;

Well, for one thing ArrayList isn't generic... did you mean List<Customer>?

您可以使用 Type.GetType(字符串)来得到一个类型的名称相关的键入对象。如果程序集是不是非此即彼的mscorlib或当前正在执行的类型,你需要包括程序集名称。无论哪种方式,你需要的空间了。

You can use Type.GetType(string) to get the Type object associated with a type by its name. If the assembly isn't either mscorlib or the currently executing type, you'll need to include the assembly name. Either way you'll need the namespace too.

你确定你真的需要一个泛型类型?泛型大多提供的编译时间的类型安全,这显然你不会有多大,如果你发现在执行时的类型。您的可以的发现它很有用,但...

Are you sure you really need a generic type? Generics mostly provide compile-time type safety, which clearly you won't have much of if you're finding the type at execution time. You may find it useful though...

Type elementType = Type.GetType("Customer");
Type listType = typeof(List<>).MakeGenericType(new Type[] { elementType });

object list = Activator.CreateInstance(listType);

如果需要的的与该列表什么,你可能需要做更通用的反映,但...如调用泛型方法。

If you need to do anything with that list, you may well need to do more generic reflection though... e.g. to call a generic method.

这篇关于将字符串转换为一个类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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