using System;
namespace Reflection
{
publicclassMyClass
{
publicstring MyField;
publicvoid MyMethod()
{
Console.WriteLine("调用MyMethod! MyField: {0}", MyField);
}
publicvoid MyMethod(string param)
{
Console.WriteLine("调用MyMethod! MyField: {0}. 参数: {1}", MyField, param);
}
}
}
using System;
using System.Reflection;
namespace Reflection
{
/// <summary>
publicclassReflection
{
publicstaticvoid Main()
{
// 从文件中加载程序集MyAssembly
Assembly a = Assembly.LoadFrom("MyAssembly.dll");
// 获取程序集中名为"MyClass"的Type, 这里必须用全名
Type type = a.GetType("Reflection.MyClass");
// 动态创建MyClass 的一个实例
Object obj = Activator.CreateInstance(type);
// 动态设置obj 的字段
FieldInfo field = type.GetField("MyField");
field.SetValue(obj, "动态设置的字段");
// 动态调用obj 的方法
MethodInfo method = type.GetMethod("MyMethod", newType[0]);
method.Invoke(obj, null);
method = type.GetMethod("MyMethod", newType[]{typeof(string)});
method.Invoke(obj, newObject[]{"一个参数"});
Console.Read();
}
}
}