찾다
백엔드 개발C#.Net 튜토리얼.Net 구성 파일 - ConfigurationSection을 상속하여 사용자 정의 구성 노드를 처리하는 사용자 정의 처리 클래스를 구현합니다.

IConfigurationSectionHandler를 상속하는 방법을 사용하여 사용자 정의 노드를 처리하기 위한 클래스를 정의하는 것 외에도 ConfigurationSection 클래스를 상속하여 동일한 효과를 얻을 수도 있습니다.

먼저 .Net 구성 파일에서 암묵적인 규칙에 대해 이야기해보자

노드를 구성할 때, 저장하려는 매개변수 데이터는 두 가지 방법으로 저장할 수 있습니다. 하나는 노드의 속성에 저장되고 다른 하나는 노드의 텍스트에 저장됩니다.

노드는 여러 속성을 가질 수 있지만 내부텍스트는 하나만 있기 때문에 프로그램에 추가될 수 있습니다. 이 두 가지 형태를 구별하면 복잡해집니다. 이 문제를 방지하기 위해 .net의 구성 파일은 innertext.


다음으로 테스트를 용이하게 하기 위해 이 무언의 규칙을 준수하는 사용자 정의 구성 파일을 작성합니다.

 

<mailServerGroup provider="www.baidu.com">
    <mailServers>
      <mailServer client="http://blog.csdn.net/lhc1105" address="13232@qq.com" userName="lhc" password="2343254"/>
      <mailServer client="http://blog345.csdn.net/lhc1105" address="132wdfgdsggtaewg32@qq.com" userName="dfshs水田如雅"  password="2334t243的萨芬234254"/>
      <mailServer client="http://blog436.csdn.net/lhc1105" address="132wdgadsfgdtaewg32@qq.com" userName="sdfhdfs水田如雅"  password="23ewrty2343的萨芬234254"/>
      <mailServer client="http://blo345734g.csdn.net/lhc1105" address="132wdgdfagdstaewg32@qq.com" userName="sdfher水田如雅"  password="23erwt43的萨芬234254"/>
    </mailServers>
  </mailServerGroup>

다음으로 해당 처리 클래스를 작성합니다. 여기서는 내부에서 외부로 작성합니다.

첫 번째는 가장 안쪽의 mailServer입니다.

 /// <summary>
    /// Class MailServerElement:用于映射mailServer节点,这里是实际存储数据的地方;
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:51:57</remarks>
    public sealed class MailServerElement : ConfigurationElement  //配置文件中的配置元素
    {

        /// <summary>
        /// Gets or sets the client.
        /// </summary>
        /// <value>The client.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:40</remarks>
        [ConfigurationProperty("client", IsKey = true, IsRequired = true)]  //client是必须的key属性,有点儿主键的意思,例如,如果定义多个client相同的节点,循环读取的话就只读取到最后一个值
        public string Client
        {
            get
            {
                return this["client"] as string;
            }
            set
            {
                this["client"] = value;
            }

        }
        /// <summary>
        /// Gets or sets the address.
        /// </summary>
        /// <value>The address.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:38</remarks>
        [ConfigurationProperty("address")]
        public string Address
        {
            get
            {
                return this["address"] as string;
            }
            set
            {
                this["address"] = value;
            }

        }
        /// <summary>
        /// Gets or sets the name of the user.
        /// </summary>
        /// <value>The name of the user.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:35</remarks>
        [ConfigurationProperty("userName")]
        public string UserName
        {

            get
            {
                return this["userName"] as string;
            }
            set
            {
                this["userName"] = value;
            }

        }
        /// <summary>
        /// Gets or sets the password.
        /// </summary>
        /// <value>The password.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:33</remarks>
        [ConfigurationProperty("password")]
        public string Password
        {

            get
            {
                return this["password"] as string;
            }
            set
            {
                this["password"] = value;
            }

        }



    }

다음은 mailServers의 모음인 mailServers입니다.

 /// <summary>
    /// Class MailServerCollection:映射mailServers节点,为一个集合类,另外还包含了很多对节点的操作方法,大部分继承自ConfigurationElementCollection
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:52:00</remarks>
    public sealed class MailServerCollection : ConfigurationElementCollection
    {
        /// <summary>
        /// 获取 <see cref="T:System.Configuration.ConfigurationElementCollection" /> 的类型。
        /// </summary>
        /// <value>The type of the collection.</value>
        /// <returns>此集合的 <see cref="T:System.Configuration.ConfigurationElementCollectionType" />。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:08</remarks>
        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
         
        }


        /// <summary>
        /// 当在派生的类中重写时,创建一个新的 <see cref="T:System.Configuration.ConfigurationElement" />。
        /// </summary>
        /// <returns>新的 <see cref="T:System.Configuration.ConfigurationElement" />。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:03</remarks>
        protected override ConfigurationElement CreateNewElement()
        {
            return new MailServerElement();
        }

        /// <summary>
        /// 在派生类中重写时获取指定配置元素的元素键。
        /// </summary>
        /// <param name="element">要为其返回键的 <see cref="T:System.Configuration.ConfigurationElement" />。</param>
        /// <returns>一个 <see cref="T:System.Object" />,用作指定 <see cref="T:System.Configuration.ConfigurationElement" /> 的键。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:04:51</remarks>
        protected override object GetElementKey(ConfigurationElement element)
        {
            return (element as MailServerElement).Client;
        }

        /// <summary>
        /// 获取在派生的类中重写时用于标识配置文件中此元素集合的名称。
        /// </summary>
        /// <value>The name of the element.</value>
        /// <returns>集合的名称;否则为空字符串。默认值为空字符串。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 23:41:40</remarks>
        protected override string ElementName
        {
            get
            {
                return "mailServer";
            }
        }


        /// <summary>
        /// 获取集合中的元素数。
        /// </summary>
        /// <value>The count.</value>
        /// <returns>集合中的元素数。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:08:24</remarks>
        public new int Count
        {
            get { return base.Count; }
        }

        /// <summary>
        /// 获取或设置此配置元素的属性、特性或子元素。
        /// </summary>
        /// <param name="index">The index.</param>
        /// <returns>MailServerElement.</returns>
        /// <remarks>Editor:v-liuhch</remarks>
        public MailServerElement this[int index]
        {

            get { return BaseGet(index) as MailServerElement; }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }

        }

        /// <summary>
        /// 获取或设置此配置元素的属性、特性或子元素。
        /// </summary>
        /// <param name="Name">The name.</param>
        /// <returns>MailServerElement.</returns>
        /// <remarks>Editor:v-liuhch</remarks>
        new public MailServerElement this[string Name]
        {
            get { return BaseGet(Name) as MailServerElement; }
        }

        /// <summary>
        /// Indexes the of.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns>System.Int32.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:24:16</remarks>
        public int IndexOf(MailServerElement element)
        {

            return BaseIndexOf(element);
        }

        /// <summary>
        /// Adds the specified element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:26:06</remarks>
        public void Add(MailServerElement element)
        {
            BaseAdd(element);
        }

        /// <summary>
        /// Removes the specified element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:27:01</remarks>
        public void Remove(MailServerElement element)
        {
            if (BaseIndexOf(element) > 0)
            {
                BaseRemove(element.Client);
            }
        }

        /// <summary>
        /// Removes at.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:33:29</remarks>
        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        /// <summary>
        /// Removes the specified client.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:34:04</remarks>
        public void Remove(string client)
        {
            BaseRemove(client);
        }

        /// <summary>
        /// Clears this instance.
        /// </summary>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:34:29</remarks>
        public void Clear()
        {
            BaseClear();
        }
    }

마지막은 가장 바깥쪽 그룹입니다:

 /// <summary>
    /// Class MailServerSection 为入口:
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:41:02</remarks>
    public class MailServerSection : ConfigurationSection   //继承配置文件中节
    {
        /// <summary>
        /// Gets the provider.:映射mailServerGroup节点的provider
        /// </summary>
        /// <value>The provider.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:59</remarks>
        [ConfigurationProperty("provider", IsKey = true)]
        public string provider { get { return this["provider"] as string; } }

        /// <summary>
        /// Gets or sets the mail servers.:映射新添加的节点mailServers节点;这个节点下还包含了若干个mailServer节点,因此它是一个集合类
        /// </summary>
        /// <value>The mail servers.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:56</remarks>
        [ConfigurationProperty("mailServers", IsDefaultCollection = false)]
        public MailServerCollection MailServers
        {
            get
            {
                return this["mailServers"] as MailServerCollection;
            }
            set
            {
                this["mailServers"] = value;
            }

        }
    }

마지막으로 연관 처리 클래스 및 노드:

 <section name="mailServerGroup" type="继承ConfigurationSection基类.MailServerSection,继承ConfigurationSection基类"/>   
  </configSections>

그런 다음 테스트를 수행합니다.

class Program
    {
        static void Main(string[] args)
        {
            Test();

        }

        /// <summary>
        /// Tests this instance.:读取节点值示例
        /// </summary>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 23:04:53</remarks>
        private static void Test() {

            MailServerSection mailSection = (MailServerSection)ConfigurationManager.GetSection("mailServerGroup");
            Console.WriteLine("MailServerSection 的provider属性值:"+mailSection.provider);
            foreach (MailServerElement config in mailSection.MailServers)
            {
                Console.WriteLine("----------------------------------");
                Console.WriteLine("client值为:"+config.Client);
                Console.WriteLine("address值为:"+config.Address);
                Console.WriteLine("username值为:"+config.UserName);
                Console.WriteLine("password值为:"+config.Password);
                Console.WriteLine("----------------------------------");
            }

            Console.ReadKey();

        }

    }

원래는 결과 사진도 올리고 싶은데 인터넷 속도가 느려서, 놀고 싶어하는 아이들이 직접 결과를 실행해볼 수 있어요. . . . .

위는 .Net 구성 파일의 내용입니다 - ConfigurationSection을 상속하여 사용자 정의 구성 노드를 처리하는 사용자 정의 처리 클래스를 구현합니다. 자세한 내용은 PHP 중국어 웹사이트를 참고하세요. (www.php.cn)!






성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
如何在 Windows 11 上启用或禁用 eSIM如何在 Windows 11 上启用或禁用 eSIMSep 20, 2023 pm 05:17 PM

如果你从移动运营商处购买了笔记本电脑,则很可能可以选择激活eSIM并使用手机网络将计算机连接到Internet。有了eSIM,您无需将另一张物理SIM卡插入笔记本电脑,因为它已经内置。当您的设备无法连接到网络时,它非常有用。如何检查我的Windows11设备是否兼容eSIM卡?单击“开始”按钮,然后转到“网络和互联网”&gt;“蜂窝&gt;设置”。如果您没有看到“蜂窝移动网络”选项,则您的设备没有eSIM功能,您应该选中其他选项,例如使用移动设备将笔记本电脑连接到热点。为了激活和

超全!Python中常见的配置文件写法超全!Python中常见的配置文件写法Apr 11, 2023 pm 10:22 PM

为什么要写配置文件这个固定文件我们可以直接写成一个 .py 文件,例如 settings.py 或 config.py,这样的好处就是能够在同一工程下直接通过 import 来导入当中的部分;但如果我们需要在其他非 Python 的平台进行配置文件共享时,写成单个 .py 就不是一个很好的选择。这时我们就应该选择通用的配置文件类型来作为存储这些固定的部分。目前常用且流行的配置文件格式类型主要有 ini、json、toml、yaml、xml 等,这些类型的配置文件我们都可以通过标准库或第三方库来进

如何在 Windows 11 中更改网络类型为专用或公共如何在 Windows 11 中更改网络类型为专用或公共Aug 24, 2023 pm 12:37 PM

设置无线网络很常见,但选择或更改网络类型可能会令人困惑,尤其是在您不知道后果的情况下。如果您正在寻找有关如何在Windows11中将网络类型从公共更改为私有或反之亦然的建议,请继续阅读以获取一些有用的信息。Windows11中有哪些不同的网络配置文件?Windows11附带了许多网络配置文件,这些配置文件本质上是可用于配置各种网络连接的设置集。如果您在家中或办公室有多个连接,这将非常有用,因此您不必每次连接到新网络时都进行所有设置。专用和公用网络配置文件是Windows11中的两种常见类型,但通

win10用户配置文件在哪? Win10设置用户配置文件的方法win10用户配置文件在哪? Win10设置用户配置文件的方法Jun 25, 2024 pm 05:55 PM

最近有不少Win10系统的用户想要更改用户配置文件,但不清楚具体如何操作,本文将给大家带来Win10系统设置用户配置文件的操作方法吧!Win10如何设置用户配置文件1、首先,按下“Win+I”键打开设置界面,并点击进入到“系统”设置。2、接着,在打开的界面中,点击左侧的“关于”,再找到并点击其中的“高级系统设置”。3、然后,在弹出的窗口中,切换到“”选项栏,并点击下方“用户配

分享几个.NET开源的AI和LLM相关项目框架分享几个.NET开源的AI和LLM相关项目框架May 06, 2024 pm 04:43 PM

当今人工智能(AI)技术的发展如火如荼,它们在各个领域都展现出了巨大的潜力和影响力。今天大姚给大家分享4个.NET开源的AI模型LLM相关的项目框架,希望能为大家提供一些参考。https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel是一种开源的软件开发工具包(SDK),旨在将大型语言模型(LLM)如OpenAI、Azure

C#的就业前景如何C#的就业前景如何Oct 19, 2023 am 11:02 AM

无论您是初学者还是有经验的专业人士,掌握C#将为您的职业发展铺平道路。

在Ubuntu上安装Helm在Ubuntu上安装HelmMar 20, 2024 pm 06:41 PM

Helm是Kubernetes的一个重要组件,它通过将配置文件捆绑到一个称为HelmChart的包中来简化Kubernetes应用程序的部署。这种方法使得更新单个配置文件比修改多个文件更加便捷。借助Helm,用户可以轻松地部署Kubernetes应用程序,简化了整个部署过程,提高了效率。在本指南中,我将介绍在Ubuntu上实现Helm的不同方法。请注意:以下指南中的命令适用于Ubuntu22.04以及所有Ubuntu版本和基于Debian的发行版。这些命令经过测试,应该在您的系统上正常运行。在U

超全!Python 中常见的配置文件写法超全!Python 中常见的配置文件写法Apr 13, 2023 am 08:31 AM

为什么要写配置文件在开发过程中,我们常常会用到一些固定参数或者是常量。对于这些较为固定且常用到的部分,往往会将其写到一个固定文件中,避免在不同的模块代码中重复出现从而保持核心代码整洁。这个固定文件我们可以直接写成一个 .py 文件,例如 settings.py 或 config.py,这样的好处就是能够在同一工程下直接通过 import 来导入当中的部分;但如果我们需要在其他非 Python 的平台进行配置文件共享时,写成单个 .py 就不是一个很好的选择。这时我们就应该选择通用的配置文件类型来

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.