Skip to main content
 首页 » 编程设计

C#之如何使用反射调用具有可变数量参数的静态方法

2024年02月06日11mfrbuaa

我想通过反射来识别以下方法:

String.Concat(params string[] args); 

这是我试过的:

MethodInfo concatMethod = typeof(string).GetMethod("Concat", new Type[] { typeof(string[]) }); 

方法被正确识别,但是当我尝试调用它时:

object concatResult = concatMethod.Invoke(null, new object[] { "A", "B" }); 

我得到以下异常:

TargetParameterCountException: Parameter count mismatch. 

另请注意,我将 null 作为实例参数传递给 Invoke 方法,这是因为该方法是静态的,因此不需要实例。这种做法是否正确?

PS:我想模拟下面的调用:

String.Concat("A", "B"); 

请您参考如下方法:

输入数组的每个元素都是方法的参数。您拥有的 Concat 重载采用单个 string[] 参数,因此您需要:

object concatResult = concatMethod.Invoke(null, new object[] { new string[] { "A", "B" } });