Before reflection was used, the common practice for cross-project-level calls was to add references at the project level.
Example: If the Client class calls the MysqlHelper class
First generate the MysqlHelper project,
Then add MysqlHelper to the Client class .dll,
Then instantiate it in the Client method, and then call the method.
After using reflection, you can configure and use it more flexibly.
As shown above, the client needs to call the database interface. We don’t know which database to hardcode here (MySQL, SQLServer, Oracle...)
Define the interface first. Assume that the interface has only one method Query(). Various DBs need to implement this interface. Then the newly added DB type will not affect the original project, thus realizing the open and closed principle (closed to modifications, closed to extensions). open).
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 query from OracleDbHelper"); } } }
MySqlDbHelper.cs
using System; using IHelper; namespace MySqlHelper{ public class MySqlDbHelper :DbHelper { public override void Query() { base.Query(); Console.WriteLine("This is query method from MySqlDbHelper"); } } }
Client side Program.cs call:
Call the database Place the dll and pdb files generated by the helper project in the client bin directory, then 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 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 result
The above is the content of C# Reflection reflection. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!