Home  >  Article  >  Backend Development  >  .Net configuration file - reflection + configuration file storage type example

.Net configuration file - reflection + configuration file storage type example

黄舟
黄舟Original
2017-02-24 10:26:021326browse

Configuration file+reflection really removes the tedious selection of statements, bringing beautiful rush!

# First of all, I improved the class (connected above):

namespace ClassLib
{
    /// <summary>
    /// Interface IGreetingStrategy
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/28 11:01:58</remarks>
    public interface IGreetingStrategy
    {
        string GreetingType { get; }
        void SetGreetingWords(ITextControl textContrl);
    }

    /// <summary>
    /// Class EnglishGreeting
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/28 11:02:38</remarks>
    public class EnglishGreeting : IGreetingStrategy
    {
        public string GreetingType
        {
            get { return "English"; }
        }

        public void SetGreetingWords(ITextControl textContrl)
        {
            textContrl.Text = "hello,readers";
        }
    }

    /// <summary>
    /// Class ChineseGreeting
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/28 11:02:56</remarks>
    public class ChineseGreeting : IGreetingStrategy
    {
        private string greetingType;
        public ChineseGreeting(string greetingType)
        {

            this.greetingType = greetingType;
        }
        public ChineseGreeting() : this("中文") { }
        public ChineseGreeting(XmlNode section) {
            XmlAttribute attr = section.SelectSingleNode("params").Attributes["greetingType"];//获取属性值
            greetingType = attr.Value;//为字段赋值
        }
        public string GreetingType
        {
            get { return greetingType; }
        }

        public void SetGreetingWords(ITextControl textContrl)
        {
            textContrl.Text = "你好啊,小读者!";
        }
    }

    /// <summary>
    /// Class GeneralClass:这个类可能还有很多的字段,属性,方法,这里只是简写下
    /// PS:GeneralClass是一个普通的类型,这个类内部维护着IGreetingStrategy,调用的时候还是根据多态具体调用。
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/28 11:08:04</remarks>
    public class GeneralClass
    {
        private IGreetingStrategy gs;
        public GeneralClass(IGreetingStrategy gs)
        {
            this.gs = gs;
        }
        public string GeneralProperty
        {
            get
            {
                //做一些额外的工作,这里省略
                return "<span sytle=&#39;color:red&#39;>" + gs.GreetingType + "</span>";
            }
        }
        public void GeneralMethod(ITextControl textContrl)
        {
            //做一些额外的工作,这里省略
            gs.SetGreetingWords(textContrl);
            textContrl.Text = "<span sytle=&#39;color:red&#39;>" + textContrl.Text + "</span>";
            //省略。。。。。。。
        }


    }

}

Then define the specific category and and the specific category and the specific class we want to use in the configuration file. Custom tag handler:

  <!--greetingStrategy节点及其处理程序配置-->
  <configSections>
    <section name="greetingStrategy" type="ClassLib.GreetingConfigurationHandler,ClassLib"/>
  </configSections>
  <greetingStrategy type="ClassLib.ChineseGreeting,ClassLib">
    <params greetingType="***中文问候***"/>  <!--构造函数的参数-->
  </greetingStrategy>

Here, ChineseGreeting is the class we want to use, and the above definition is the class that handles greetingStrategy;

Next, write the specific implementation of this class:

namespace ClassLib
{
    public class GreetingConfigurationHandler : IConfigurationSectionHandler
    {
        /*
         处理有参数的构造函数的对象的创建:
         */
        /// <summary>
        /// 创建配置节处理程序。
        /// </summary>
        /// <param name="parent">父对象。</param>
        /// <param name="configContext">配置上下文对象。</param>
        /// <param name="section">节 XML 节点。</param>
        /// <returns>创建的节处理程序对象。</returns>
        /// <exception cref="System.NotImplementedException"></exception>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/30 20:34:54</remarks>
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            //获取节点type属性的值
            Type t = Type.GetType(section.Attributes["type"].Value);
            object obj=null;

            try
            {
                /* 2,在要实例的类中加入一个构造函数,接收一个XmlNode节点,将greeting_stragetgy的节点在此传递,然后在这个构造函数中进行处理;*/
                //如果t包含有参数为xmlnode的构造函数,直接使用这个构造函数
                Type[] paras = { typeof(XmlNode) };
                ConstructorInfo constructors = t.GetConstructor(paras);
                if (constructors != null)
                {
                    object[] paramters = { section };
                    return Activator.CreateInstance(t, paramters); //传入读取到的构造函数的参数
                }

                if (section.SelectSingleNode("params") == null)  //无参数构造函数
                {
                    obj = Activator.CreateInstance(t);
                }
                else  //有参数构造函数
                {
                    /*1,在此类中对策略类进行处理,取得params节点的属性值,然后传递给具体实例化的类;*/

                    //获取params节点的属性greetingType的值
                    XmlAttribute attr = section.SelectSingleNode("params").Attributes["greetingType"];
                    object[] parameters = { attr.Value };
                    obj = Activator.CreateInstance(t, parameters); //传入读取到的构造函数的参数
                } 
            }
            catch (Exception)
            {

                return null;
            }
            
            return obj ;
        }
    }
}

In the creation method, we first determine whether the ChineseGreeting class has A constructor whose parameter is a node. If there is one, use section directly as a parameter and pass it in when using reflection to create a type instance;

If there is no such constructor , we read the parameters in the XML file in this processing class, and then pass them in when the type is instantiated; It's just a matter of whether this parameter is read sooner or later; after personal comparison, I feel that the way of reading the constructor parameters in the configuration file in this class is more flexible, which is my personal preference.

:

 #region 自定义节点存储类型信息——反射方法
            IGreetingStrategy greetingStrategy = (IGreetingStrategy)ConfigurationManager.GetSection("greetingStrategy");
            if (greetingStrategy != null)
            {
                GeneralClass generalClass = new GeneralClass(greetingStrategy);
                ltrGreetingType.Text = generalClass.GeneralProperty;
                generalClass.GeneralMethod(ltrGreetingWord);
            }
            #endregion

嘿 Hey, relatively convenient.


## This feels that the reflection is strong, but where is the change of this change, it is easier to change or later maintenance The cost is low, so the configuration file should be uploaded at this time. . . . . .

The above is the content of the .Net configuration file - reflection + configuration file storage type instance. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!







#

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn