mardi 19 juin 2018

Why does invoking a method with params object[] as args throw a cast error?

I am trying to wrap my soap-calls with a generic wrapper to simplify logging and other commons.

When trying to invoke a method on the client I send in, I get this error thrown when using parameters:

{"Unable to cast object of type 'System.String' to type 'System.String[]'."}

My code:

private T CallExternalSoap<T>(object client, string funcName, params object[] args)
        {
            var type = client.GetType();

            var method = type.GetMethod(funcName);

            if (method is null)
            {
                throw new NullReferenceException($"Could not find method {funcName} on object of type {type}.");
            }

            if (method.GetParameters().Length != args.Length)
            {
                throw new Exception($"Number of parameters in {args} does not match number of expected parameters in method {funcName} . Expected {method.GetParameters().Length} parameters");
            }

            var result = (T)method.Invoke(client, args);
            return result;
        }

Calling code, which require one parameter(a string):

    object[] myObjArray = { "Sweden" };
    var client = new org.oorsprong.webservices.CountryInfoService();
    var asdads = loggy.CallExternalSoapAndLog<string[]>(client, "CountryISOCode", myObjArray);

No matter which objects/params I send in I get that error. Tried string, objects, almost anything. Any ideas?





Aucun commentaire:

Enregistrer un commentaire