. NET configuration file--Reflection + profile Storage Type instance

Source: Internet
Author: User
configuration file + reflection does remove the tedious choice of statements, bringing a beautiful bright!





first we improved the class (next to the 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"]; // Get the attribute value
            greetingType = attr.Value; // Assign a value to a field
        }
        public string GreetingType
        {
            get {return greetingType;}
        }

        public void SetGreetingWords (ITextControl textContrl)
        {
            textContrl.Text = "Hello, little reader!";
        }
    }

    /// <summary>
    /// Class GeneralClass: This class may have many fields, properties, and methods. Here is just a short write
    /// PS: GeneralClass is a common type. This class internally maintains IGreetingStrategy, and it is still called according to polymorphism.
    /// </ 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
            {
                // Do some extra work, omitted here
                return "<span sytle = 'color: red'>" + gs.GreetingType + "</ span>";
            }
        }
        public void GeneralMethod (ITextControl textContrl)
        {
            // Do some extra work, omitted here
            gs.SetGreetingWords (textContrl);
            textContrl.Text = "<span sytle = 'color: red'>" + textContrl.Text + "</ span>";
            // omitted. . . . . . .
        }


    }

}


Then define the handler for the specific class and custom labels we want to use in the configuration file:



<!-greetingStrategy node and its handler configuration->
   <configSections>
     <section name = "greetingStrategy" type = "ClassLib.GreetingConfigurationHandler, ClassLib" />
   </ configSections>
   <greetingStrategy type = "ClassLib.ChineseGreeting, ClassLib">
     <params greetingType = "*** Chinese greeting ***" /> <!-Constructor parameters->
   </ greetingStrategy>


Here, Chinesegreeting is the class we want to use, which defines the class that handles greetingstrategy;



Next, write the specific implementation of this class:




namespace ClassLib
{
    public class GreetingConfigurationHandler: IConfigurationSectionHandler
    {
        / *
         Handling the creation of an object with a parameterized constructor:
         * /
        /// <summary>
        /// Create a configuration section handler.
        /// </ summary>
        /// <param name = "parent"> the parent object. </ param>
        /// <param name = "configContext"> Configuration context object. </ param>
        /// <param name = "section"> section XML node. </ param>
        /// <returns> The section handler object created. </ 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)
        {
            // Get the value of the node type attribute
            Type t = Type.GetType (section.Attributes ["type"]. Value);
            object obj = null;

            try
            {
                / * 2, add a constructor to the class to be instantiated, receive an XmlNode node, pass the node of greeting_stragetgy here, and then process in this constructor; * /
                // If t contains a constructor with an xmlnode parameter, use this constructor directly
                Type [] paras = {typeof (XmlNode)};
                ConstructorInfo constructors = t.GetConstructor (paras);
                if (constructors! = null)
                {
                    object [] paramters = {section};
                    return Activator.CreateInstance (t, paramters); // Pass in the parameters of the read constructor
                }

                if (section.SelectSingleNode ("params") == null) // No parameter constructor
                {
                    obj = Activator.CreateInstance (t);
                }
                else // has a parameter constructor
                {
                    / * 1, process the policy class in this class, get the attribute value of the params node, and then pass it to the concrete instantiated class; * /

                    // Get the value of the attribute greetingType of the params node
                    XmlAttribute attr = section.SelectSingleNode ("params"). Attributes ["greetingType"];
                    object [] parameters = {attr.Value};
                    obj = Activator.CreateInstance (t, parameters); // Pass the parameters of the read constructor
                }
            }
            catch (Exception)
            {

                return null;
            }
            
            return obj;
        }
    }
}


In the creation method, we first determine whether the Chinesegreeting class has a parameter for the node construction method, if any, directly to the section as a parameter, in the use of reflection to create a type instance of the time passed in;



If there is no such construction method, we will read the parameters in the XML file in this processing class, and then pass it on when the type is instantiated;



two ways to compare, in fact, are the same, only through the parameter read the sooner or later the problem; In contrast to the individual, it seems more flexible and personal preference to read the constructor parameters in the configuration file in this class.



Write something under test:



#region Custom node storage type information-reflection method
             IGreetingStrategy greetingStrategy = (IGreetingStrategy) ConfigurationManager.GetSection ("greetingStrategy");
             if (greetingStrategy! = null)
             {
                 GeneralClass generalClass = new GeneralClass (greetingStrategy);
                 ltrGreetingType.Text = generalClass.GeneralProperty;
                 generalClass.GeneralMethod (ltrGreetingWord);
             }
             #endregion 


Hey, it's relatively convenient.






The feeling of reflection is strong in pulling the change out, but where the change is taken to the most easily changed or later maintenance costs are lower, so the configuration file at this time ...



The above is. NET configuration file--Reflection + profile Storage Type instance content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.