.Net/C#
[C#] Dynamic Method Call With Out Parameter
뚱2
2012. 3. 22. 12:54
해당 오프젝트의 타입을 확인하고 메소드가 존재하고 파라미터가 일치한다면
호출해 준다.
호출해 준다.
// class public class MyObject { pub int Connect() { // 접속 ... } public void GetLastError(out int errorCode, out string errorMessage) { // 내부 코드들 ... } }
// ErrorUtil public class ErrorUtil { private static readonly string methodName = "GetLastError"; private static int errorCode = 0; private static string errorMessage = ""; public static int ErrorCode { get { return errorCode; } } public static string ErrorMessage { get { return errorMessage; } } public static bool GetLastError(object obj) { try { Type t = obj.GetType(); MethodInfo info = t.GetMethod( ErrorUtil.methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(int).MakeByRefType(), typeof(string).MakeByRefType() }, null ); if (info != null) { object[] parameters = new object[2]; info.Invoke(obj, parameters); errorCode = (int)parameters[0]; errorMessage = (string)parameters[1]; return true; } else { errorMessage = String.Format("{0} 메소드를 찾을수 없거나, 파라미터가 정확하지 않습니다.", ErrorUtil.methodName); return false; } } catch (Exception ex) { errorMessage = ex.Message; return false; } } }
// 사용예 MyObject oCommpany = new MyObject(); int retCode = oCompany.Connect(); if (retCode != 0) { ErrorUtil.GetLastError(oCompany); MessageBox.Show(ErrorUtil.ErrorMessage); }