好吧,那么……

<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;

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

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

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

最佳答案

System.Configuration.ReadOnlyNameValueCollection 是 System.dll 程序集的 internal 类。所以你不能从你的代码中引用它。不过,它源自 System.Collections.Specialized.NameValueCollection ,所以这就是为什么您可以使用类型转换做到这一点。

关于c# - ReadOnlyNameValueCollection(从 ConfigurationManager.GetSection 读取),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6019228/

10-11 02:49
查看更多