C# 如何纠正参数计数不匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15926338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:30:23  来源:igfitidea点击:

how to correct the parameter count mismatch

c#reflection

提问by trupatrue

How can I correct this error I'm having

我该如何纠正我遇到的这个错误

TargetParameterCountException was unhandled by user code. Parameter count mismatch.

用户代码未处理 TargetParameterCountException。参数计数不匹配。

This is my code where it's happening

这是我发生的代码

public static void InvokeMethod(string className, string methodName, string fileName)
{
    var t = Type.GetType(className);
    using (StreamReader f = new StreamReader("params.txt"))
    {
        t.GetMethod(methodName).Invoke(t.GetConstructor(Type.EmptyTypes).Invoke(new object[] { }), new object[] { f.ReadLine() });
    }
}

This is the whole code

这是整个代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.IO;

class MyClass
{
    private int i;
    public double d;
    private string s;
    public bool b;
    public MyClass()
    {
        i = 1;
        d = 0.1;
        s = "1";
        b = true;
    }
    public void Method0()
    {
        Console.WriteLine("Method with no arguments, no return value.");
    }
    private int Method1(int arg0)
    {
        Console.WriteLine("The method returns int, int gets.");
        return arg0;
    }
    private double Method2(int arg0, double arg1)
    {
        Console.WriteLine("Method returns a double, taking int and double.");
        return arg1 * arg0;
    }
    public bool Method3(string arg0)
    {
        Console.WriteLine("Method returns a bool, accepts string");
        return arg0.Length>10;
    }
    public bool Method3(string arg0,string arg1)
    {
        Console.WriteLine("The method takes two arguments string.");
        return arg0 == arg1;
    }
    public static char Method4(string arg0)
    {
        Console.WriteLine("Method returns a char, accepts string. .");
        Console.WriteLine(arg0);
        return arg0[1];
    }
    public void Method5(int arg0, double arg1)
    {
        Console.WriteLine("arg1 = {0} arg2 = {1}.",arg0,arg1);
    }
}

class MyTestClass
{
    public static string[] GetMethodsWithStrParams(string className)
    {
        var t = Type.GetType(className);
        List<string> res = new List<string>();
        foreach (var method in t.GetMethods())
        {
            foreach (var param in method.GetParameters())
            {
                if (param.ParameterType == typeof(string))
                {
                    res.Add(method.Name);
                    break;
                }
            }
        }
        return res.ToArray();
    }
    public static void InvokeMethod(string className, string methodName, string fileName)
    {
        var t = Type.GetType(className);
        using (StreamReader f = new StreamReader("params.txt"))
        {
            t.GetMethod(methodName).Invoke(t.GetConstructor(Type.EmptyTypes).Invoke(new object[] { }),
                                           new object[] { f.ReadLine() });
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        string name = "MyClass";

        foreach (var x in MyTestClass.GetMethodsWithStrParams(name))
        {
            Console.WriteLine(x);
        }

        MyTestClass.InvokeMethod("MyClass", "Method5", "params.txt");

        Console.ReadKey(true);
    }
}

采纳答案by Zdeslav Vojkovic

Your InvokeMethodimplementation always calls t.GetMethod(methodName).Invokewith two arguments, the first being the target instance on which the method is called, and second being the array of method arguments, which contains only one string (f.ReadLine()).

您的InvokeMethod实现始终t.GetMethod(methodName).Invoke使用两个参数进行调用,第一个是调用方法的目标实例,第二个是方法参数数组,其中仅包含一个字符串 ( f.ReadLine())。

Then you use InvokeMethodto call MyClass.Method5which takes two arguments, an int and a double. This obviously can't work, as myClass.Method5("some string")is syntactically incorrect, and this is what effectively happens. You can't expect that a string is a valid argument list for all MyClassmethods, can you?

然后你使用InvokeMethod调用MyClass.Method5which 需要两个参数,一个 int 和一个 double。这显然行不通,因为myClass.Method5("some string")在语法上是不正确的,而这正是实际发生的情况。你不能指望一个字符串是所有MyClass方法的有效参数列表,对吗?

That is the cause of the error, but only you can decide how to fix it, as we don't know the greater context. You have to provide the correct number of parameters depending on the actual method being called.

这就是错误的原因,但只有您可以决定如何修复它,因为我们不知道更大的背景。您必须根据被调用的实际方法提供正确数量的参数。

Possible path to solution:

可能的解决途径:

  • what are the arguments I want to provide to Method5?
  • where do I get them from?
  • how do I move them from wherever they are to the array I give to Invoke?
  • 我想提供给 Method5 的参数是什么?
  • 我从哪里得到它们?
  • 我如何将它们从它们所在的任何地方移动到我提供的数组中 Invoke

This should get you started, but no one can tell you exactly as you have only described the error, but not the real problem you are trying to solve with your code.

这应该可以帮助您入门,但没有人能准确地告诉您您只描述了错误,而不是您试图用代码解决的真正问题。

回答by Guffa

The error doesn't need any correction, it is correct. ;)

错误不需要任何更正,它是正确的。;)

You are trying to call a method that takes two parameters with an array of parameters that only contains one item.

您正在尝试使用仅包含一个项目的参数数组来调用采用两个参数的方法。

A parameter array that would work for that specific method would for example be:

例如,适用于该特定方法的参数数组是:

new object[] { 0, 1.5 }

If you want your InvokeMethodmethod to work with methods that take different number of parameters with different types, you have to create different parameter arrays for each combination.

如果您希望您的InvokeMethod方法使用具有不同类型的不同数量参数的方法,您必须为每个组合创建不同的参数数组。