在我自己的自定义 appSettings 上使用 foreach 所需的代码
我搜索了该网站,但没有找到我想要的内容。接近,但没有雪茄。
基本上我想要一个像这样的配置部分:
<configSections>
<section name="PhoneNotificationsSection" type="Alerts.PhoneAlertConfigSection,Alerts,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null"/>
</configSections>
<PhoneNotificationsSection>
<phones>
<add phone="MyMobile" value="[email protected]" />
<add phone="OtherMobile" value="[email protected]" />
</phones>
</PhoneNotificationsSection>
然后我想在我的 appSettings 消费代码中,能够编写这样的东西(伪代码):
foreach (phone p in phones)
{
//'phone' attribute is just helpful/descriptive
DoSomething(p.value);
}
我已经做了足够的研究知道我可能需要一些我自己的类实现和/或继承某些配置类以使上述代码成为可能。我只是还没有找到任何可以清楚地演示这种情况以及如何为其编码的内容 - 当我尝试学习整个 .NET 配置世界时,我的大脑开始受伤。有人有一些像我正在寻找的代码可以分享吗?
I've searched the site and haven't found exactly what I'm looking for. Close, but no cigar.
Basically I want to have a config section like this:
<configSections>
<section name="PhoneNotificationsSection" type="Alerts.PhoneAlertConfigSection,Alerts,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null"/>
</configSections>
<PhoneNotificationsSection>
<phones>
<add phone="MyMobile" value="[email protected]" />
<add phone="OtherMobile" value="[email protected]" />
</phones>
</PhoneNotificationsSection>
Then I'd like to, in my appSettings consuming code, be able to write something like this (pseudo code):
foreach (phone p in phones)
{
//'phone' attribute is just helpful/descriptive
DoSomething(p.value);
}
I've done enough research to know I probably need a few of my own classes that implement and/or inherit from certain Configuration classes to make the above code possible. I just haven't found anything that clearly demonstrates this scenario and how to code for it - and when I try to learn the whole .NET configuration world my brain starts to hurt. Anyone have some code like what I'm looking for that they can share?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我曾经写过类似的内容,作为 C# 课程的示例。在我看来,它主要展示了 .NET 配置子系统是多么糟糕,尽管代码确实有效。我没有根据您的设置进行调整,因为很容易引入错误,并且到目前为止 SO 编辑器不会验证发布的代码示例;)
首先,配置部分声明:
为了匹配上面的代码片段,我们首先需要配置部分:
我们正在使用自定义元素集合,因此我们也声明一下:
最后我们需要声明元素集合中使用的自定义元素:
现在,完成所有这些后,我们就可以访问配置文件了。我正在使用配置器帮助程序类来使这稍微不那么麻烦:
希望这会有所帮助。
I've written something similar once, as an example for a C# course. In my opinion it mainly demonstrates how awful the .NET configuration subsystem is, although the code does work. I've not adapted it to your settings, as it's fairly easy to introduce a mistake and so far the SO editor does not validate posted code samples ;)
First, the configuration section declaration:
To match the above snippet we first need the configuration section:
We are using a custom element collection, so let's declare that too:
And finally we need to declare the custom element used in the element collection:
Now, having all this in place we're ready to access the configuration file. I'm using a Configurator helper class to make this slightly less cumbersome:
Hope this helps.