public static void TargetException() { Exception ex = new TargetException(); Assert.NotNull(ex); Assert.Equal(ex.GetType(), typeof(TargetException)); string s = "My exception"; ex = new TargetException(); Assert.NotNull(ex); Assert.Equal(ex.GetType(), typeof(TargetException)); Assert.Equal(s, ex.Message); s = "My exception"; Exception innerException = new Exception(); ex = new TargetException(s, innerException); Assert.NotNull(ex); Assert.Equal(ex.GetType(), typeof(TargetException)); Assert.Equal(innerException, ex.InnerException); Assert.Equal(s, ex.Message); // Throw the exception from a method. try { ThrowTargetException(s, innerException); Assert.True(false); } catch (TargetException tex) { Assert.Equal(innerException, tex.InnerException); Assert.Equal(s, tex.Message); } catch (Exception) { Assert.True(false); } }
private static object CallMethodWithByRefParametersOrThrow(Type type, object target, string methodName, object[] args, TargetException te) { MethodInfo[] mis = type.GetMethods(); foreach(MethodInfo mi in mis) { ParameterInfo[] parameters = mi.GetParameters(); if ((mi.Name.Equals(methodName)) && (parameters.Length == args.Length)) { bool allMatch = true; IList<int> byRefArgIndices = new List<int>(); for(int i=0; i<parameters.Length; i++) { Type rawParameterType = parameters[i].ParameterType; Type parameterType = rawParameterType.IsByRef?rawParameterType.GetElementType():rawParameterType; if (!(parameterType.IsAssignableFrom(args[i].GetType()))) { allMatch = false; break; } else if (rawParameterType.IsByRef) { byRefArgIndices.Add(i); } } if (allMatch) { object invocationResult = mi.Invoke(target, args); if (byRefArgIndices.Count == 0) { return invocationResult; } else { object[] result = new object[1 + byRefArgIndices.Count]; result[0] = invocationResult; for(int i=0; i<byRefArgIndices.Count; i++) { result[1+i] = args[byRefArgIndices[i]]; } return result; } } } } throw te; }