ReadOnlyNameValueCollection(从ConfigurationManager.GetSection读取)

fea*_*net 7 .net c# asp.net types configurationmanager

好的,所以......

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

var test = ConfigurationManager.GetSection("test");
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.调试器显示test包含一个键,foo.

但是GetSection回归object,所以我们需要一个演员:

var type = test.GetType();
// FullName: System.Configuration.ReadOnlyNameValueCollection
// Assembly: System
Run Code Online (Sandbox Code Playgroud)

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

using System;

var test = ConfigurationManager
               .GetSection("test") as ReadOnlyNameValueCollection;
Run Code Online (Sandbox Code Playgroud)

错误!

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

错... wtf?

一个演员来System.Collections.Specialized.NameValueCollection获取代码工作,但我真的不明白为什么错误.

ReadOnlyNameValueCollection在MSDN上搜索显示该类没有任何文档.它似乎不存在.然而,我的代码中有一个这种类型的实例.

Tim*_*Tim 14

System.Configuration.ReadOnlyNameValueCollectioninternalSystem.dll程序集的类.所以你不能从你的代码中引用它.它来源于System.Collections.Specialized.NameValueCollection,所以这就是为什么你能够用演员来做到这一点.

  • 它看起来有点奇怪,但函数的返回类型实际上是`object`所以它不像它们直接暴露内部类型(甚至不编译,我不相信).由于它来自公共类型,您可以使用该对象.从我所知道的,"GetSection"的意思是你知道什么时候你打电话给它,你期望从中得到什么.因此,只要有*某些东西*可以投射到有效的东西,这似乎是合理的.当返回类型确实是基类型时,我把它比作返回内部派生类型.没有问题,对吗? (2认同)