帮助使用ConfigurationSection正确读取配置文件

Lit*_*ers 4 c# xml web-config configurationsection

我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)

Fly*_*wat 5

这里的魔力是使用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; }
   }

}
Run Code Online (Sandbox Code Playgroud)

等等...

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

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