using System;
namespace ClassLibrary1
{
public class Class1
{
public Class1()
{
}
public int GetSum(int x, int y)
{
//return x + y;
return 11;
}
}
}
System.Reflection.Assembly a = System.Reflection.Assembly.LoadFrom("ClassLibrary1.DLL");
System.Type t = a.GetType("ClassLibrary1.Class1");
//动态生成ClassLibrary1.Class类的实例
Object theObj = System.Activator.CreateInstance(t);
//参数信息,GetSum需要两个int参数
System.Type[] paramTypes = new System.Type[2];
paramTypes[0] = System.Type.GetType("System.Int32");
paramTypes[1] = System.Type.GetType("System.Int32");
System.Reflection.MethodInfo mi = t.GetMethod("GetSum", paramTypes);
//参数值
Object[] parameters = new Object[2];
parameters[0] = 3;
parameters[1] = 4;
Object returnValue = mi.Invoke(theObj, parameters);
textBox1.Text = returnValue.ToString();
Console.WriteLine("ClassLibrary1.Class1.GetSum(3, 4) returns: {0}", returnValue.ToString());
///////////////////////
using System;
using System.Reflection;
public class MyClass
{
public int i = 10;
public int j = 2;
public int MyFunc(int i , int j)
{
int k;
k = i * 10 - j;
return k;
}
}
public class Type_GetMethod
{
public static void Main()
{
try
{
// Get the type of MyClass.
Type myType = typeof(MyClass);
// Get the method information for MyFunc(int, int).
MemberInfo myMemberInfo = myType.GetMethod("MyFunc", BindingFlags.Public |
BindingFlags.Instance,
null,
CallingConventions.Any,
new Type[] {typeof(int),typeof(int)},
null);
Console.WriteLine("\nDisplaying information for MyFunc: \n");
// Display the method information.
Console.WriteLine("{0}", myMemberInfo);
}
catch(Exception e)
{
Console.WriteLine("Exception : {0}", e.Message);
}
}
}