Since reflection is used in the project, it is prepared to write each class library first in the configuration file, then read the configuration file, and then reflect the class library that is configured in the configuration file.
The benefit of this is that each class library remains independent, where a problem with one class library does not affect other class libraries, as long as the individual DLLs are updated when the project is updated.
1. First look at how the configuration file is configured
The custom node processors is created in the configuration file above, and then the method node is corresponding below the processors node.
Two methods were used in the above project, so two nodes were created. Type represents the assembly name, and method represents the name.
2. See how to use the configuration file
[HTML]View Plaincopy
- private void Button1_Click (object sender, EventArgs e)
- {
- Returns the node name and metadata information in the configuration file
- IDictionary<string,methodinfo> dic=loadappconfig (application.startuppath + "\ \ App. Config ");
- Test GetInfo method
- var mi = dic["GetInfo"];
- var obj = activator.createinstance (mi. DeclaringType);
- Object[] para={"Hello"};//if the length of the array does not match the number of arguments, the exception will be reported
- Return method Result Value
- Object result = mi. Invoke (obj, para);
- MessageBox.Show (result. ToString ());
- }
- <summary>
- Reading configuration Files
- </Summary>
- <param name="path"></param>
- <returns></returns>
- Private Dictionary<string, MethodInfo> Loadappconfig (string filename)
- {
- var processors = new Dictionary<string, MethodInfo> ();
- var xml = new XmlDocument ();
- Xml. Load (filename);
- foreach (XmlNode node in XML. SelectNodes ("configuration/processors/*"))
- {
- if (node. NodeType! = xmlnodetype.element)
- Continue
- var method = node. Name;
- Try
- {
- String TypeName = node. attributes["type"]. value;//assembly name
- String MethodName = node. Attributes["Method"]. value;//Method Name
- var t = Type.GetType (typeName);
- var m = T.getmethod (methodName);
- processors. Add (MethodName, M);
- }
- catch (Exception e)
- {
- }
- }
- return processors;
- }
Demo Download: http://download.csdn.net/detail/zx13525079024/4734769
http://blog.csdn.net/zx13525079024/article/details/8149517
C # reflects on configuration files