字符串转换为键入C# [英] Convert String to Type in C#

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

问题描述

如果我收到一封包含一个类(对象)的名称的字符串,我想这个字符串转换为一个真正的类型(一个字符串中),我该怎么办呢?

If I receive a string that contains the name of a class (object) and I want to convert this string to a real type (the one in the string), how can I do this?

我试过

Type.GetType("System.Int32")

有例如,它似乎工作

但是,当我尝试用我自己的对象,它总是返回null ...

But when I try with my own object, it always returns null ...

我不知道会是怎样的字符串中提前所以这是我唯一的来源,将其转换为它真正的类型。

I have no idea what will be in the string in advance so it's my only source for converting it to its real type.

Type.GetType("NameSpace.MyClasse");

你知道吗?

推荐答案

您只能使用的只是的(当然,它的命名空间,)类型的名称,如果该类型是的mscorlib 或调用程序集。否则,你必须包括程序集的名称,以及:

You can only use just the name of the type (with its namespace, of course) if the type is in mscorlib or the calling assembly. Otherwise, you've got to include the assembly name as well:

Type type = Type.GetType("Namespace.MyClass, MyAssembly");

如果该程序集强命名,你一定要包括所有的信息了。请参阅 Type.GetType(字符串) <文档/ A>了解更多信息。

If the assembly is strongly named, you've got to include all that information too. See the documentation for Type.GetType(string) for more information.

另外,如果你有一个参考的装配体已经(例如,通过一个著名的类型),可以使用的 Assembly.GetType

Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use Assembly.GetType:

Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType(namespaceQualifiedTypeName);

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

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