当我用反射调用一个类的方法 如果这个方法出了异常 我发现不能把异常正常抛上去。比如
"seelect * from Customers"这个错误的sql语句执行后会出一个"*附近有语法错误"得异常,
抛上去以后 反射调用的那边只能捕获到这样一个异常"调用的目标出现了错误",我想获得 反射调用的类的异常应该怎么做?

解决方案 »

  1.   

    定义一个接口,调用接口不要用MethodInfo.Invoke
      

  2.   

    try{
    //反射操作
    }catch(System.Reflection.TargetInvocationException ex) {
    throw ex.InnerException;
    }
      

  3.   

    这是.net的帮助文档:
    创建 TargetInvocationException 后,向其传递对通过反映调用的方法所引发的异常的引用。InnerException 属性保存基础异常。也就是说只要取到这个异常的InnerException属性,就是你要的那个异常
      

  4.   

    //compute.cs
    public class Compute
    {
    public Compute()
    {
    //
    // TODO: 在此处添加构造函数逻辑
    //
    }
    public static double Div(int before,int behide)
    {
    return before/behide;
    }
    }
    //class1.cs
    using Dll;
    /// <summary>
    /// Class1 的摘要说明。
    /// </summary>
    class Class1
    {
    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
    Type t = typeof(Compute);
    BindingFlags Divflag = BindingFlags.InvokeMethod;
    Object[] input = new object[]{4,0};
    try
    {
    Object result = t.InvokeMember("Div",Divflag,null,"Computer",input);
    }
    catch(TargetInvocationException ex)
    {
    Console.WriteLine(ex.InnerException.Message);
    }
    Console.WriteLine("Game Over");
    }
    }
    OK !~散分!~!
      

  5.   

    throw new Exception(ex.InnerException.Message);