关于C#的运行时动态操作以前写过两篇《C# 运行时动态对象创建》、《C#动态方法调用》,本篇将再介绍几个实用函数,以方便使用。 public static class RuntimeHelper { public static object InvokeMember(string methodName, object target, params object[] args) { return target.GetType().InvokeMember(methodName, System.Reflection.BindingFlags.InvokeMethod, null, target, args); } public static object InvokeStaticMember(string methodName, Type targetType, params object[] args) { return targetType.InvokeMember(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static, null, null, args); } public static object InvokeGetProperty(string methodName, object target, params object[] args) { return target.GetType().InvokeMember(methodName, System.Reflection.BindingFlags.GetProperty, null, target, args); } public static object InvokeStaticGetProperty(string methodName, Type targetType, params object[] args) { return targetType.InvokeMember(methodName, System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Static, null, null, args); } public static T Parse<T>(string str) { return (T)InvokeStaticMember("Parse", typeof(T), str); } public static T Parse<T>(string str, T defaultValue) { T result; TryParse<T>(str, out result, defaultValue); return result; } public static bool TryParse<T>(string str, out T result, T defaultValue) { object[] args = new object[] { str, null }; if ((bool)typeof(T).InvokeMember("TryParse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static, null, null, args)) { result = (T)args[1]; return true; } else { result = defaultValue; return false; } } } |
|