简体   繁体   English

为什么将带有params object []的方法作为args引发转换错误?

[英]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[]'."} {“无法将类型为“ System.String”的对象转换为类型为“ 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;
}

No matter which objects/params I send in I get that error. 无论我发送哪个对象/参数,都会收到该错误。 Any ideas? 有任何想法吗?

The issue is not with the parameters but with casting the result. 问题不在于参数,而在于转换结果。

The SOAP method is returning a string but you are casting as a string[] based on the type parameter. SOAP方法返回一个字符串,但是您将根据类型参数将其转换为string []。

CallExternalSoap<string[]>(...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么Roslyn不会为方法统一抛出错误? - Why does Roslyn not throw an error for method unification? 为什么 (int)(object)10m 抛出“指定的强制转换无效”异常? - Why does (int)(object)10m throw "Specified cast is not valid" exception? 为什么此块引发错误? - Why does this block throw an error? 我们如何使用 `params object[] args` 将可变数量的参数传送到另一种方法? - How do we barrel a variable number of params using `params object[] args` to another method? 为什么我的代码会引发无效的强制转换异常? (C#)? - Why does my code throw an Invalid Cast Exception? (C#)? 为什么调用Add在强制转换为ICollection的集合中引发异常 <T> ? - Why does calling Add throw an exception in a collection cast to ICollection<T>? 为什么“params object[]”需要作为“new object[] { parameters }”传递给 Com Method? - Why does "params object[]" need passing as "new object[] { parameters }" for Com Method? 对对象的方法调用不会引发异常 - Method call on object does NOT throw exception 为什么&#39;{&#39;在静态方法中抛出NullReferenceException? - Why does the '{' throw a NullReferenceException in a static method? 为什么这个字符串扩展方法不会抛出异常? - Why does this string extension method not throw an exception?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM