转
Activator.CreateInstance(ClassName) 至于调用,使用用接口做约束,反射调用性能很低
/// <summary>
/// 调用远程方法
/// </summary>
/// <param name="assemblyFile">程序集名称</param>
/// <param name="typeName">类型名称</param>
/// <param name="methodName">方法名称</param>
/// <param name="parameters">参数列表</param>
/// <returns>无返回值则返回null</returns>
public object InvokeRemoteMethod(string assemblyFile, string typeName, string methodName, object[] parameters)
{
try
{
// 加载程序集
System.Reflection.Assembly Ay = System.Reflection.Assembly.LoadFrom(assemblyFile);
// 获取程序集中所有公共类型
Type[] tps = Ay.GetExportedTypes();
object returnValue = null;
// 遍历所获取的类型
foreach (Type tp in tps)
{
if (tp.Name == typeName)
{
returnValue = tp.GetMethod(methodName).Invoke(System.Activator.CreateInstance(tp), parameters);
break;
}
}
return returnValue;
}
catch
{
return null;
}
}
例:InvokeRemoteMethod("ClassA.dll", "a1", "Test", null)
例:
[类库:ClassLibrary2.dll]
namespace ClassLibrary2
{
public class MyClass
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public string Test()
{
return this.Name;
}
}
}
[应用程序]
private void button1_Click(object sender, EventArgs e)
{
// 加载程序集
System.Reflection.Assembly Ay = System.Reflection.Assembly.LoadFrom("ClassLibrary2.dll");
// 获取程序集中所有公共类型
Type[] tps = Ay.GetExportedTypes();
// 遍历所有公共类型
foreach (Type tp in tps)
{
if (tp.Name == "MyClass")
{
// 创建类型实例
object obj = System.Activator.CreateInstance(tp);
// 设置实例属性值
tp.GetProperty("Name").SetValue(obj, "123456",null);
// 调用方法,显示返回值
MessageBox.Show(tp.GetMethod("Test").Invoke(obj, null).ToString());
}
}
}
//获取类型信息
//如果调用其他的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)
{
}