//获取类型信息
//如果调用其他的DLL
//System.Reflection.Assembly asmb = System.Reflection.Assembly.LoadFrom("DLL名");
// Type t = asmb.GetType("类名");
//如果是不调用其他DLL
System.Type t = System.Type.GetType("类名");
try
{
object dObj = Activator.CreateInstance(t);
//获取方法的信息
System.Reflection.MethodInfo method = t.GetMethod("方法名");
//调用方法的一些标志位,这里的含义是Public并且是实例方法,这也是默认的值
System.Reflection.BindingFlags flag = System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Instance;
//GetValue方法的参数
object[] parameters = new object[] { "参数1" };
//object returnValue = method.Invoke(dObj, flag, Type.DefaultBinder,
parameters, null);
//取得方法返回的值
object returnValue = method.Invoke(dObj, flag, Type.DefaultBinder,
parameters, null);
}
catch(Exception ex)
{
}
下面是我自己写的一个Reflection类,可以根据类名,方法名执行方法
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Reflection;
namespaceSearchFromDB
{
classReflection
{
stringClassName="";
Type clstype;
publicReflection(stringClassName)
{
this.ClassName = ClassName;
}
publicReflection()
{
}
///
/// 实例对象时需要指定类名
///
publicobjectGetClassInstance(stringassembly ,stringNameSpace)
{
//assembly为程序集名称,NameSpace为命名空间
clstype = Assembly.Load(assembly).GetType(string.Concat(NameSpace,".",this.ClassName));
if(clstype ==null)
returnnull;
objectobj = (object)Activator.CreateInstance(clstype);
returnobj;
}
///
/// 实例对象时不用指定类名
///
publicobjectGetClassInstance(stringassembly,stringNameSpace,stringclassname)
{
ClassName = classname;
clstype = Assembly.Load(assembly).GetType(string.Concat(NameSpace,".", classname));
if(clstype ==null)
returnnull;
objectobj = (object)Activator.CreateInstance(clstype);
returnobj;
}
///
/// 执行类的静态方法
///
///
/// 类的方法名
///
///
/// 方法的参数类型
///
///
/// 方法的参数
///
publicobjectGetMethod(stringmethodname, Type[] methodtype,object[] parameters)
{
// methodtype.SetValue(typeof(string),1);
System.Reflection.MethodInfo pMethod = clstype.GetMethod(methodname, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public, null, methodtype,null);
//调用方法的一些标志位,这里的含义是Public并且是实例方法,这也是默认的值
//System.Reflection.BindingFlags flag = BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public;
objectreturnValue = pMethod.Invoke(null, parameters);
//string returnValue = pMethod.Invoke(clsObj, flag, Type.DefaultBinder, parameters,null).ToString();
returnreturnValue;
}
}
}
本文介绍如何使用C#反射机制加载类并调用其方法,包括从指定DLL中获取类型信息及执行静态方法的具体步骤。

2637

被折叠的 条评论
为什么被折叠?



