假如我有这么一个类
class Employee
{
string name;
void GetPaid( int amount ) {}
int reward() {}
class Task
{ int cycles = 3; }
}
在C#, 类默认的访问类型是内部internal 即在一个Assembly内是可以访问的, assembly可以是单独的一个dll,exe文件等。但是类的成员变量默认是private。当我做单元测试需要测试这些私有函数的时候,C#像Java一样提供了反射Reflection机制来帮助你访问私有成员。
using System.Reflection;
static void main()
{
Type type = typeof(Employee);
Employee employee = (Employee)type.GetConstructor(System.Type.EmptyTypes).Invoke(null); // 实例化对象
MethodInfo method1 = type.GetMethod("GetPaid", BindingFlags.NonPublic | BindingFlags.Instance); // 获得GetPaid方法
method1.Invoke(employee, new Object[] { 2000 }); // 调用方法,传递对象employee和参数
MethodInf