【问题标题】:Help with using ConfigurationSection to properly read from a config file帮助使用 ConfigurationSection 正确读取配置文件
【发布时间】:2010-09-20 06:39:45
【问题描述】:

我正在尝试创建类以使用 ConfigurationSection 和 ConfigurationElementCollection 从我的配置文件中读取,但我遇到了困难。

作为配置示例:


<PaymentMethodSettings>
  <PaymentMethods>
    <PaymentMethod name="blah blah" code="1"/>
    <PaymentMethod name="blah blah" code="42"/>
    <PaymentMethod name="blah blah" code="43"/>
    <Paymentmethod name="Base blah">
      <SubPaymentMethod name="blah blah" code="18"/>
      <SubPaymentMethod name="blah blah" code="28"/>
      <SubPaymentMethod name="blah blah" code="38"/>
    </Paymentmethod>
  </PaymentMethods>
</PaymentMethodSettings>

【问题讨论】:

  • 你能告诉我你想做什么吗?我的意思是当我不知道它背后的原因时,我提供一个 XMLReader 似乎相当侮辱
  • 他想在.NET中使用内置的配置类,而不是手动解析文件。

标签: c# xml web-config configurationsection


【解决方案1】:

这里的神奇之处在于使用 ConfigurationSection 类。

这些类只需要包含与您的配置架构 1:1 匹配的属性。您可以使用属性让 .NET 知道哪些属性与哪些元素匹配。

因此,您可以创建 PaymentMethod 并让它从 ConfigurationSection 继承

您将创建 SubPaymentMethod 并让它从 ConfigurationElement 继承。

PaymentMethod 将在其中包含 SubPaymentMethods 的 ConfigurationElementCollection 作为属性,这就是您将复杂类型连接在一起的方式。

您无需编写自己的 XML 解析代码。

public class PaymentSection : ConfigurationSection
{
   // Simple One
   [ConfigurationProperty("name")]]
   public String name
   {
      get { return this["name"]; }
      set { this["name"] = value; }
   }

}

等等……

请参阅此处了解如何创建 ConfigurationElementCollections 以便您可以拥有嵌套类型:

http://blogs.neudesic.com/blogs/jason_jung/archive/2006/08/08/208.aspx

【讨论】:

    【解决方案2】:

    This 应该可以帮助您弄清楚如何正确创建配置部分,然后从中读取。

    【讨论】:

      猜你喜欢
      • 2011-02-19
      • 1970-01-01
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      相关资源
      最近更新 更多