作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试调用通过反射接受单个 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/
我是一名优秀的程序员,十分优秀!