1、可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型
2、应用程序需要在运行时从某个特定的程序集中载入一个特定的类型,以便实现某个任务时可以用到反射。
3、反射主要应用与类库,这些类库需要知道一个类型的定义,以便提供更多的功能。
与工厂模式的联系:
利用反射,在配置文件里定义好类型名,在程序运行时动态创建对象。调高了灵活性,但会有性能损失
工厂方法+反射:
using System;
using System.Collections.Generic;
using System.Text;
namespace FactoryMethod
{
abstract class AbstractCar
{
public abstract void StartUp();
public abstract void Run();
public abstract void Turn();
public abstract void Stop();
}
abstract class AbstractCarFactory
{
public abstract AbstractCar CreateCar();
}
class DongFengCarFactory : AbstractCarFactory
{
public override AbstractCar CreateCar()
{
return new DongfengCar();
}
}
class HongQiCarFactory : AbstractCarFactory
{
public override AbstractCar CreateCar()
{
return new HongQiCar();
}
}
class DongfengCar : AbstractCar
{
public override void StartUp()
{
}
public override void Run()
{
}
public override void Turn()
{
}
public override void Stop()
{
}
}
class HongQiCar : AbstractCar
{
public override void StartUp()
{
}
public override void Run()
{
}
public override void Turn()
{
}
public override void Stop()
{
}
}
class CarTestFrameWork
{
AbstractCar car;
public void BuildTesetContext(AbstractCarFactory abstractCarFactory)
{
car = abstractCarFactory.CreateCar();
}
public void DoTest()
{
Console.WriteLine("Test " + car.ToString() + " car!");
}
public void GetData()
{
}
}
//这个类里使用了反射
class Program
{
static void Main(string[] args)
{
CarTestFrameWork carTestFrameWork = new CarTestFrameWork();
String strCarFactory = "FactoryMethod." + ConfigurationSettings.AppSettings["CarFactory"];
string carFactoryType = "";
AbstractCarFactory carFactory;
carFactory = Assembly.Load("FactoryMethod").CreateInstance(strCarFactory) as AbstractCarFactory;
carTestFrameWork.BuildTesetContext(carFactory);
carTestFrameWork.DoTest();
Console.ReadLine();
}
}
}
配置文件定义:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="CarFactory" value="DongFengCarFactory"/>
</appSettings>
</configuration> |