


.Net configuration file - reflection + configuration file storage type example
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='color:red'>" + gs.GreetingType + "</span>"; } } public void GeneralMethod(ITextControl textContrl) { //做一些额外的工作,这里省略 gs.SetGreetingWords(textContrl); textContrl.Text = "<span sytle='color:red'>" + 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)!
#

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The reflection mechanism allows programs to obtain and modify class information at runtime. It can be used to implement reflection of interfaces and abstract classes: Interface reflection: obtain the interface reflection object through Class.forName() and access its metadata (name, method and field) . Reflection of abstract classes: Similar to interfaces, you can obtain the reflection object of an abstract class and access its metadata and non-abstract methods. Practical case: The reflection mechanism can be used to implement dynamic proxies, intercepting calls to interface methods at runtime by dynamically creating proxy classes.

You can use reflection to access private fields and methods in Go language: To access private fields: obtain the reflection value of the value through reflect.ValueOf(), then use FieldByName() to obtain the reflection value of the field, and call the String() method to print the value of the field . Call a private method: also obtain the reflection value of the value through reflect.ValueOf(), then use MethodByName() to obtain the reflection value of the method, and finally call the Call() method to execute the method. Practical case: Modify private field values and call private methods through reflection to achieve object control and unit test coverage.

Recently, many Win10 system users want to change the user profile, but they don’t know how to do it. This article will show you how to set the user profile in Win10 system! How to set up user profile in Win10 1. First, press the "Win+I" keys to open the settings interface, and click to enter the "System" settings. 2. Then, in the opened interface, click "About" on the left, then find and click "Advanced System Settings". 3. Then, in the pop-up window, switch to the "" option bar and click "User Configuration" below.

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

Helm is an important component of Kubernetes that simplifies the deployment of Kubernetes applications by bundling configuration files into a package called HelmChart. This approach makes updating a single configuration file more convenient than modifying multiple files. With Helm, users can easily deploy Kubernetes applications, simplifying the entire deployment process and improving efficiency. In this guide, I'll cover different ways to implement Helm on Ubuntu. Please note: The commands in the following guide apply to Ubuntu 22.04 as well as all Ubuntu versions and Debian-based distributions. These commands are tested and should work correctly on your system. in U

Go language reflection allows you to manipulate variable values at runtime, including modifying Boolean values, integers, floating point numbers, and strings. By getting the Value of a variable, you can call the SetBool, SetInt, SetFloat and SetString methods to modify it. For example, you can parse a JSON string into a structure and then use reflection to modify the values of the structure fields. It should be noted that the reflection operation is slow and unmodifiable fields cannot be modified. When modifying the structure field value, the related fields may not be automatically updated.

Reflection provides type checking and modification capabilities in Go, but it has security risks, including arbitrary code execution, type forgery, and data leakage. Best practices include limiting reflective permissions, operations, using whitelists or blacklists, validating input, and using security tools. In practice, reflection can be safely used to inspect type information.

The reflection feature in the Go language allows a program to inspect and modify the structure of a type at runtime. By using Type, Value and reflect.Kind, we can obtain the type information, field values and methods of the object, and we can also create and modify objects. Specific operation methods include: checking type (TypeOf()), obtaining field value (ValueOf(), FieldByName()), modifying field value (Set()), and creating object (New()).
