电の岁月---点滴记忆
交流,分享,进步

用“反射”替代switch语句

//实例化方法一
//原来我们把一个类实例化是这样的
Animal animal=new Cat(); //声明一个动物对象,名称叫animal,然后将animal实例化成猫类的对象

//实例化方法二
//我们还可以用反射的办法得到这个实例
using System.Reflection;//先引用System.Reflection
//假设当前程序集是AnimalSystem,名称空间也是AnimalSystem
Animal animal = (Animal)Assembly.Load("AnimalSystem").CreateInstance("AnimalSystem.Cat");

关键是

Assembly.Load("程序集名称").CreateInstance("名称空间.类名称")

上面的例子更改为:

将add(),sub()等逻辑算法提取出来,独立成类(add.cs,sub.cs)

namespace simple
{
  //将interface从Form1中提出来,这样add.cs和sub.cs才可以使用此接口
public interface operation
{
int operate(int a, int b);
}
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

public class Factory
{
public operation getore(string s)
{
try
{
DataSet ds
= new DataSet();
ds.ReadXml(Application.StartupPath
+ "\\operation.xml");
DataRow dw
= ((DataRow[])ds.Tables[0].Select("name='" + s + "'"))[0];
return (operation)Assembly.Load("simple").CreateInstance("simple." + dw["class"].ToString());
}
catch (Exception g)
{
MessageBox.Show(g.Message);
return null;
}

}
}
private void button1_Click(object sender, EventArgs e)
{
Factory f
= new Factory();
textBox3.Text
=f.getore(comboBox1.Text).operate(Int32.Parse(textBox1.Text),Int32.Parse(textBox2.Text)).ToString();
}
}
}

其中operation.xml的内容为:

<?xml version="1.0" encoding="utf-8" ?>
<operation>
<operator>
<name>+</name>
<class>add</class>
</operator>
<operator>
<name>-</name>
<class>sub</class>
</operator>
</operation>

“反射”可以用在选择的场合,自动的选择合适的类...

 

优点:无需修改客户端,假如需要增加新的运算,如*等,只需要编写相当的类mul.cs,然后在配置文件operation.xml
中添加name和class属性值即可...

 

 

 

 

posted on 2010-08-11 20:23  doucontorl  阅读(259)  评论(0编辑  收藏  举报