Maison  >  Article  >  développement back-end  >  .Net——使用.net内置处理程序处理自定义节点Demo

.Net——使用.net内置处理程序处理自定义节点Demo

黄舟
黄舟original
2017-02-24 10:34:221467parcourir

在.net中,因为对不同的节点,都对应着类去对它进行处理,。net里面为了方便,已经内置了一些类供我们使用,使我们在读取配置文件时,不必自己去定义类去处理自己定义的自定义节点。

下面我们写了这样一个配置文件:  

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <!--使用IgnoreSection处理自定义节点-->
    <!--<section name="mailServeraddress" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false " restartOnExternalChanges="true"/>-->

    <section name="mailServeraddress" type="System.Configuration.SingleTagSectionHandler" />
    
    <!--注意,指定处理程序的配置文件要写在自定义配置文件的前面-->
  </configSections>
  
  
  <mailServeraddress address="mail.tracefact.net" username="lhc" password="124324"/>

 
</configuration>

节点名称为:mailServeraddress,有三个属性,在section里定义了SingleTagSectionHandler来处理这个节点。

namespace 自定义节点和内置处理程序
{
    class Program
    {
        static void Main(string[] args)
        {
            ExampleSingleTagSectionHandler();

        }

        private static void ExampleSingleTagSectionHandler() {
            //SingleTagSectionHandler会以hashtable的形式返回节点的所有属性
            Hashtable mailServer = (Hashtable)ConfigurationManager.GetSection("mailServeraddress");//调用GetSection会返回一个hashtable

            string address = mailServer["address"].ToString();
            string username = mailServer["username"].ToString();
            string passWord = mailServer["password"].ToString();

            Console.WriteLine(address+"----"+username+"------"+passWord);

            
        }
    }
}

配置文件写好后,调用GetSection强转hashtable后,就可以用key——value的形式读取节点的属性值了。

 在.net中,除了上面例子中的这个type,我们也可以使用其它内置type来处理自定义节点。


 以上就是.Net——使用.net内置处理程序处理自定义节点Demo 的内容,更多相关内容请关注PHP中文网(www.php.cn)!










Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn