反射:动态加载和使用类一例
在.net 2.0里面,有一个很好用的反射,如果能恰如其分的使用,可以大大的简化我们的编码.
在这里结合一个例子来说明它的使用.
按照程序员的风格,先贴代码:
/// <summary>
/// 获取对象
/// </summary>
/// <param name="className">实体类名称</param>
/// <returns></returns>
public static Object GetObeject ( string className)
{
Type objType;
Assembly assembly;
assembly = Assembly.Load ( "MyProject.Bussiness" );
objType = assembly.GetType ( "MyProject.Bussiness." + className+ "Rule" );
ArrayList arr = new ArrayList ( );
string methodName="Get"+table;
MethodInfo mii = objType.GetMethod ( methodName, new Type[ ] { typeof ( ArrayList ) } );
Object obj = mii.Invoke ( null, new object[ ] { arr } );
return obj;
}
说明: 在我的运用中,每个实体类都对应有一个业务类,业务类的命名规则是实体类名称+Rule,例如我有一个实体类A.cs,它对应的业务类名为:ARule.cs.
在每个业务类中都有一个名为Get+类名的方法,参数为一个ArrayList(例:GetA(arrayList)),该方法获取对应实体类的对象.
assembly = Assembly.Load ( "MyProject.Bussiness" );//动态加载业务类程序集(业务类所在的命名空间).
objType = assembly.GetType ( "MyProject.Bussiness." + className+ "Rule" );//获取当前业务类
ArrayList arr = new ArrayList ( );
string methodName="Get"+table;
生成一个参数实例和表名.
主角入场了:
MethodInfo mii = objType.GetMethod ( methodName, new Type[ ] { typeof ( ArrayList ) } );//传入参数,获取实力方法.
Object obj = mii.Invoke ( null, new object[ ] { arr } );//调用方法,获取对象实例.
到此为止,整个过程结束,是不是很快?!
我们来看看它的三步走:
1 加载程序集
2 准备工作(获取类,方法,参数等)
3 调用,返回结果
收工.
只要按照上面的要求来组织程序,不管你有多少实体类,都可以用上面的方法类获取类实例对象,是不是很简约?
在这里结合一个例子来说明它的使用.
按照程序员的风格,先贴代码:
/// <summary>
/// 获取对象
/// </summary>
/// <param name="className">实体类名称</param>
/// <returns></returns>
public static Object GetObeject ( string className)
{
Type objType;
Assembly assembly;
assembly = Assembly.Load ( "MyProject.Bussiness" );
objType = assembly.GetType ( "MyProject.Bussiness." + className+ "Rule" );
ArrayList arr = new ArrayList ( );
string methodName="Get"+table;
MethodInfo mii = objType.GetMethod ( methodName, new Type[ ] { typeof ( ArrayList ) } );
Object obj = mii.Invoke ( null, new object[ ] { arr } );
return obj;
}
说明: 在我的运用中,每个实体类都对应有一个业务类,业务类的命名规则是实体类名称+Rule,例如我有一个实体类A.cs,它对应的业务类名为:ARule.cs.
在每个业务类中都有一个名为Get+类名的方法,参数为一个ArrayList(例:GetA(arrayList)),该方法获取对应实体类的对象.
assembly = Assembly.Load ( "MyProject.Bussiness" );//动态加载业务类程序集(业务类所在的命名空间).
objType = assembly.GetType ( "MyProject.Bussiness." + className+ "Rule" );//获取当前业务类
ArrayList arr = new ArrayList ( );
string methodName="Get"+table;
生成一个参数实例和表名.
主角入场了:
MethodInfo mii = objType.GetMethod ( methodName, new Type[ ] { typeof ( ArrayList ) } );//传入参数,获取实力方法.
Object obj = mii.Invoke ( null, new object[ ] { arr } );//调用方法,获取对象实例.
到此为止,整个过程结束,是不是很快?!
我们来看看它的三步走:
1 加载程序集
2 准备工作(获取类,方法,参数等)
3 调用,返回结果
收工.
只要按照上面的要求来组织程序,不管你有多少实体类,都可以用上面的方法类获取类实例对象,是不是很简约?

浙公网安备 33010602011771号