为什么我不能动态构造 System.Xml.XmlDocument?

发布于 2024-08-05 21:45:08 字数 203 浏览 7 评论 0原文

以下代码失败,并显示“无法从程序集中加载类型‘System.Xml.XmlDocument’”错误:

object a = Type.GetType("System.Xml.XmlDocument", true);

我有对 XmlDocument 所在的 System.Xml 的引用。

知道我做错了什么吗?

The following code fails with a 'Could not load type 'System.Xml.XmlDocument' from assembly' error:

object a = Type.GetType("System.Xml.XmlDocument", true);

I have a reference to System.Xml in which XmlDocument resides.

Any idea what I am doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

唔猫 2024-08-12 21:45:08

如果您需要能够从字符串动态加载它,这将起作用,您必须指定完全限定名称,因为 GAC 中可能有此 dll 的多个版本。根据您使用的框架版本,将 Version=2.0.0.0 替换为您要加载的版本。

Assembly xmlAssembly = Assembly.Load("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

加载程序集后,您就可以动态创建所需类的实例。

object xmlDoc = xmlAssembly.CreateInstance("System.Xml.XmlDocument", false);

If you need to be able to dynamically load it from a string, this will work, you must specify the fully qualified name because there are possibly multiple versions of this dll in the GAC. Replace the Version=2.0.0.0 with the version you want to load depending on the framework version you are using.

Assembly xmlAssembly = Assembly.Load("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

Once you have loaded the assembly, you can then dynamically create an instance of the class you are after.

object xmlDoc = xmlAssembly.CreateInstance("System.Xml.XmlDocument", false);
瀞厅☆埖开 2024-08-12 21:45:08

使用完全限定名称,因为程序集可能尚未加载:

object a = Type.GetType("System.Xml.XmlDocument, System.Xml", true);

Use a fully qualified name, since the assembly may not yet have been loaded:

object a = Type.GetType("System.Xml.XmlDocument, System.Xml", true);
秋心╮凉 2024-08-12 21:45:08

通常只需附加一个逗号和程序集名称即可完成,即“Namespace.Type, Assembly”。但是,如果程序集是强命名的(如 System.Xml.dll),则需要使用 Type.AssemblyQualifiedName 属性,该属性不仅返回“Namespace.Type, Assembly”,还返回标识程序集所需的签名信息。这有效:

var xmlDocType = Type.GetType("System.Xml.XmlDocument, System.Xml, "
    + "Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")

You can usually get by just by appending a comma and the assembly name, i.e. "Namespace.Type, Assembly". However, if an assembly is strongly named, as System.Xml.dll is, you need to use the Type.AssemblyQualifiedName property which returns not just "Namespace.Type, Assembly" but also the signature information required to identify the assembly. This works:

var xmlDocType = Type.GetType("System.Xml.XmlDocument, System.Xml, "
    + "Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文