用C#在做服务器开发时,在处理服务器与客户端的响应时用到了C#的反射(通过字符串调用对应的函数)。
具体代码如下:
/// <summary> /// 反射(Controller:类名;RequestCode:枚举类型;ActionCode:枚举类型;BaseController:各类Controller类的基类; /// 通过RequestCode找到对应的Controller类,再通过ActionCode找到对应Controller类中的方法 /// 将枚举类型转换为字符串,再根据字符串找到对应名字的类和类中的方法) /// <summary> /// <param> /// _data,_client是作为形参传入到ActionCode对应的方法中(这里根据需求传入所需个数和类型的形参) /// <param> public void HandleRequest(RequestCode _requestCode, ActionCode _actionCode, string _data, Client _client) { BaseController controller = null; //m_controllerDic:字典,将枚举RequestCode和Controller类对应,方便查找 bool isGet = m_controllerDic.TryGetValue(_requestCode, out controller); if (!isGet) { Console.WriteLine("无法得到" + _requestCode + "所对应的Controller类"); return; } string methodName = Enum.GetName(typeof(ActionCode), _actionCode); //枚举类型转换为字符串 MethodInfo methodInfo = controller.GetType().GetMethod(methodName); //通过反射的机制得到controller中的方法 if (methodInfo == null) //当没有得到Controller中方法信息时 { Console.WriteLine("[警告]在Controller[" + controller.GetType() + "]中没有对应的处理方法:[" + methodName + "]"); return; } object[] parameters = new object[] { _data, _client}; //controller类中methodName的方法带的参数 object obj = methodInfo.Invoke(controller, parameters); //调用controller类中methodName的方法 if (obj == null || string.IsNullOrEmpty(obj as string)) //当methodName的方法返回的值为空时(不为空时返回给客户端) { return; } }