The common practice for cross-project-level calls is to add references at the project level before reflection is used.
Example: The Client class calls the Mysqlhelper class.
First build the Mysqlhelper project,
Then add the MysqlHelper.dll in the Client class,
The method is then instantiated in the Client's method and then called.
With reflection, you can configure it more flexibly and use it flexibly.
For example, the client wants to invoke the database interface, the database here we do not explicitly write hard code which database (MySQL, SQL Server, Oracle ... )
The interface is defined here, assuming that the interface has only one method Query (), the various DB needs to implement the interface, then the newly added DB type will not affect the original project, thus implementing the open closure principle (closed to the modification, open to the extension).
Interface Class DbHelper.cs
Using System;namespace ihelper{public class DBHelper {public dbhelper () { Console.WriteLine (" This is DBHelper construction "); } Public virtual void query () { Console.WriteLine ("This is Query method"); } }
OracleDbHelper.cs
Using system;using ihelper; namespace oraclehelper{public class Oracledbhelper:dbhelper {public override void Query () { Base. Query (); Console.WriteLine ("This is a query from Oracledbhelper");}}}
MySqlDbHelper.cs
Using system;using ihelper; namespace mysqlhelper{public class Mysqldbhelper:D bhelper {public override void Query () { Base. Query (); Console.WriteLine ("This is the query method from Mysqldbhelper");}}}
Client Side Program.cs Call:
Put the DLL, PDB file generated by the database Help class project into the client bin directory, add the configuration in App. Config, and then use the Assembly class under Reflection to implement it.
Program.cs
static void Main (string[] args) { string config = configurationsettings.appsettings["DBHelper"]; Assembly Assembly = assembly.load (config. Split (', ') [0]); Type typehelper = assembly. GetType (config. Split (', ') [1]); Object ohelper = Activator.CreateInstance (typehelper); DBHelper DBHelper = (dbhelper) ohelper; Dbhelper.query (); Console.read ();}
Client Side App. Config configuration:
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <startup> <supportedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/> </startup> <appSettings> <!--<add key=" DBHelper "Value=" Mysqlhelper,mysqlhelper.mysqldbhelper "/>--> <add key=" DBHelper "value=" OracleHelper, Oraclehelper.oracledbhelper "/> </appSettings></configuration>
Run results
The above is the content of C # Reflection reflection, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!