ReadOnlyNameValueCollection(从 ConfigurationManager.GetSection 读取)
好吧,所以......
<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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
System.Configuration.ReadOnlyNameValueCollection
是 System.dll 程序集的一个内部
类。所以你不能从你的代码中引用它。不过,它派生自 System.Collections.Specialized.NameValueCollection,因此您可以通过强制转换来实现此目的。System.Configuration.ReadOnlyNameValueCollection
is aninternal
class to the System.dll assembly. So you can't refer to it from your code. It derives fromSystem.Collections.Specialized.NameValueCollection
, though, so that's why you're able to do that with the cast.