新建一个控制台应用程序
Bike中的代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 反射 { public class Bike : ICar { public void Light() { Console.WriteLine("我有1个灯"); } public void Wheel() { Console.WriteLine("我有2个轮子"); } } }
Car中的代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 反射 { public class Car : ICar { public void Light() { Console.WriteLine("我有8个灯"); } public void Wheel() { Console.WriteLine("我有4个轮子"); } } }
Factory中的代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //引用配置和反射 using System.Configuration; using System.Reflection; namespace 反射 { public class Factory { private static string InterfaceName = ConfigurationManager.AppSettings["InterfaceName"]; public ICar GetCar() { //第一个是程序集名称,第二个是命名空间.类名 return (ICar)Assembly.Load("反射").CreateInstance("反射" + "." + InterfaceName); } } }
ICar中的代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 反射 { public interface ICar { void Wheel(); void Light(); } }
Program中的代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 反射 { class Program { static void Main(string[] args) { Factory factory = new Factory(); ICar Result = factory.GetCar(); Result.Light(); Result.Wheel(); Console.ReadLine(); } } }
App.config中的配置
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <appSettings> <add key="InterfaceName" value="Car" /> </appSettings> </configuration>