Invoke、InvokeMember提示“调用的目标发生了异常”
使用 InnerException 就可以显示出反射调用里头的错误信息。
- void fn(int n)
- {
- if (n >= 10)
- return;
- throw new ArgumentException("参数必须大于10");
- }
- Type type = typeof(Program);
- object instance = Activator.CreateInstance(type);
- MethodInfo mi = type.GetMethod("fn", BindingFlags.NonPublic | BindingFlags.Instance);
- try
- {
- mi.Invoke(instance, new object[] { null });
- }
- catch(TargetInvocationException targetEx)
- {
- if (targetEx.InnerException != null)
- {
- throw targetEx.InnerException;
- }
- }