mardi 30 janvier 2018

How to get a parameter value passed as a reference with MethodInfo.Invoke when throws an exception in the invoked method

I would like to know what is the value of an out/ref parameter of a invoked method.

When the method is invoked without throws an exception, the value is received in the parameter, but I do not get the value when an exception throws in the invoked method. Invoking directly the method without Reflection, the value is received.

Am I doing something wrong or is this a .net limitation?

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        string[] arguments = new string[] { bool.FalseString, null }; 
        MethodInfo method = typeof(Program).GetMethod("SampleMethod");
        try
        {
            method.Invoke(null, arguments);
            Console.WriteLine(arguments[1]); // arguments[1] = "Hello", Prints Hello
            arguments = new string[] { bool.TrueString, null };
            method.Invoke(null, arguments);
        }
        catch (Exception)
        {
            Console.WriteLine(arguments[1]); // arguments[1] = null, Does not print
        }
        arguments[1] = null;
        try
        {
            SampleMethod(bool.TrueString, out arguments[1]);
        }
        catch (Exception)
        {
            Console.WriteLine(arguments[1]); // arguments[1] = "Hello"
        }
    }

    public static void SampleMethod(string throwsException, out string text)
    {
        text = "Hello";
        if (throwsException == bool.TrueString)
            throw new Exception("Test Exception");
    }
}





Aucun commentaire:

Enregistrer un commentaire