在 C# 中将字符串转换为类型

Convert String to Type in C#(在 C# 中将字符串转换为类型)
本文介绍了在 C# 中将字符串转换为类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我收到一个包含类名的字符串,并且我想将此字符串转换为真实类型(字符串中的那个),我该怎么做?

If I receive a string that contains the name of a class 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")

例如,它似乎可以工作.

for example, it appears to work.

但是当我尝试使用自己的对象时,它总是返回 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(string) 了解更多信息.

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# 中将字符串转换为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)