ReadOnlyNameValueCollection(从 ConfigurationManager.GetSection 读取)

发布于 2024-11-07 21:06:35 字数 1006 浏览 9 评论 0原文

好吧,所以......

<section name="test" type="System.Configuration.NameValueFileSectionHandler" />
<test>
   <add key="foo" value="bar" />
</test>

var test = ConfigurationManager.GetSection("test");

到目前为止一切顺利。调试器显示 test 包含一个键 foo

但是 GetSection 返回 object,所以我们需要一个强制转换:

var type = test.GetType();
// FullName: System.Configuration.ReadOnlyNameValueCollection
// Assembly: System

好的,这应该很简单。所以......

using System;

var test = ConfigurationManager
               .GetSection("test") as ReadOnlyNameValueCollection;

错误!

命名空间 System.Configuration 中不存在类型或命名空间 ReadOnlyNameValueCollection。您是否缺少程序集引用?

呃...wtf?

转换为 System.Collections.Specialized.NameValueCollection 可使代码正常工作,但我不太明白为什么会出现错误。

在 MSDN 上搜索 ReadOnlyNameValueCollection 显示根本没有关于此类的文档。它似乎不存在。然而我的代码中有一个这种类型的实例。

Ok, so.....

<section name="test" type="System.Configuration.NameValueFileSectionHandler" />
<test>
   <add key="foo" value="bar" />
</test>

var test = ConfigurationManager.GetSection("test");

So far so good. The debugger shows test contains one key, foo.

But GetSection returns object, so we need a cast:

var type = test.GetType();
// FullName: System.Configuration.ReadOnlyNameValueCollection
// Assembly: System

Ok, this should be simple enough. So....

using System;

var test = ConfigurationManager
               .GetSection("test") as ReadOnlyNameValueCollection;

error!

The type or namespace ReadOnlyNameValueCollection does not exist in the namespace System.Configuration. Are you missing an assembly reference?

err... wtf?

A cast to System.Collections.Specialized.NameValueCollection gets the code working, but I don't really understand why the error.

And a search for ReadOnlyNameValueCollection on MSDN shows there is no documentation on this class at all. It doesn't seem to exist. Yet I have an instance of that type in my code.

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

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

发布评论

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

评论(1

∞梦里开花 2024-11-14 21:06:36

System.Configuration.ReadOnlyNameValueCollection 是 System.dll 程序集的一个内部类。所以你不能从你的代码中引用它。不过,它派生自 System.Collections.Specialized.NameValueCollection,因此您可以通过强制转换来实现此目的。

System.Configuration.ReadOnlyNameValueCollection is an internal class to the System.dll assembly. So you can't refer to it from your code. It derives from System.Collections.Specialized.NameValueCollection, though, so that's why you're able to do that with the cast.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文