/// <summary> /// 测试调用 方法. /// </summary> public void TestCall() { // 创建实例. Object obj = new ObjectClass(); // 首先取得类型 Type myType = obj.GetType(); Console.WriteLine("测试 通过反射调用 HelloWorld 方法。"); myType.GetMethod("HelloWorld").Invoke(obj, null); Console.WriteLine("测试 通过反射调用 GetHelloWorld() 方法。"); Object returnVal = myType.GetMethod("GetHelloWorld", new Type[]{}).Invoke(obj, null); Console.WriteLine("返回值 = " + returnVal); Console.WriteLine("测试 通过反射调用 GetHelloWorld(String name) 方法。"); returnVal = myType.GetMethod("GetHelloWorld", new Type[] { typeof(String) }).Invoke(obj, new Object[]{"Xixi"}); Console.WriteLine("返回值 = " + returnVal); }
/// <summary> /// 测试 读取/设置 属性. /// </summary> public void TestGetSetProp() { // 创建实例. Object obj = new ObjectClass(); // 首先取得类型 Type myType = obj.GetType(); // 通过属性名字,首先获取属性 GetProperty("TestProp") // 然后通过属性,设置值 SetValue myType.GetProperty("TestProp").SetValue(obj, "HaHa", null); // 测试 属性的值是否被正确的设置. Console.WriteLine("检查 SetValue 执行结果:" + ((ObjectClass)obj).TestProp); // 通过属性名字,首先获取属性 GetProperty("TestProp") // 然后通过属性,获取值 GetValue Object testVal = myType.GetProperty("TestProp").GetValue(obj, null); // 测试 属性的值是否被正确的获取. Console.WriteLine("检查 GetValue 执行结果:" + testVal); }