gpt4 book ai didi

c# - 通过反射调用带有 params 参数的泛型方法

转载 作者:行者123 更新时间:2023-12-03 23:09:19 25 4
gpt4 key购买 nike

我正在尝试调用通过反射接受单个 params 参数的通用方法。当我选择它为非通用时,传递 object[] 项似乎就足够了,但当我需要调用通用方法时,它不再起作用。

var type = typeof (ClassWithGenericMethod);
var method = type.GetMethod("GenericMethod", BindingFlags.Instance | BindingFlags.Public);
var genericMethod = method.MakeGenericMethod(typeof(object));
var result = (bool)genericMethod.Invoke(new ClassWithGenericMethod(), new object[]{"param"});
Assert.IsTrue(result);

被调用的类:

public class ClassWithGenericMethod
{
public bool GenericMethod<T>(params string[] input)
{
return input.Length == 1;
}
}

代码在断言之前失败,但出现以下异常:

Object of type 'System.String' cannot be converted to type 'System.String[]'.

最佳答案

尝试用 new object[] { new[] { "param"} } 替换 new object[]{"param"}

这里new object[]是参数数组,第一个参数应该是string[],但是在你的代码中,你使用了 string,因此出现异常。

关于c# - 通过反射调用带有 params 参数的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35404295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com