C# 使用多个参数调用,导致FormatException

C# 使用多个参数调用,导致FormatException,c#,invoke,C#,Invoke,我试图从另一个线程调用表单方法。在form课程中,我有: delegate int ReplaceMessageCallback(string msg, int key); public int ReplaceMessage(string msg, int key) { if (this.InvokeRequired) { ReplaceMessageCallback amc = new ReplaceMessageCallback(ReplaceMessage

我试图从另一个线程调用表单方法。在form课程中,我有:

delegate int ReplaceMessageCallback(string msg, int key);

public int ReplaceMessage(string msg, int key)
{
    if (this.InvokeRequired)
    {
        ReplaceMessageCallback amc = new ReplaceMessageCallback(ReplaceMessage);
        object[] o = new object[] { msg, key };
        return (int)this.Invoke(amc, o);
    }
    bool found = false;
    int rv;

    lock (this)
    {
        if (key != 0)
        {
            found = RemoveMessage(key);
        }
        if (found)
        {
            rv = AddMessage(msg, key);
        }
        else
        {
            rv = AddMessage(msg);
        }
    }

    MainForm.EventLogInstance.WriteEntry((found) 
                        ? EventLogEntryType.Information 
                        : EventLogEntryType.Warning,
            IntEventLogIdent.MessageFormReplace1,
            String.Format("MessageForm::ReplaceMessage(({2},{0}) returns {1}.\n\n(The message {3} exist to be replaced.)",
                key,
                rv,
                msg,
                (found) 
                    ? "did" 
                    : "did not"));
    return rv;
}
运行此操作时,我在调用时收到一个异常“FormatException was unhandled”“索引(基于零)必须大于或等于零且小于参数列表的大小。”


本质上,这个代码片段在只接受一个参数的类方法上工作得很好,所以我假设我对对象数组做了一些错误,但我不知道是什么

处理此问题的更简单方法是:

if (this.InvokeRequired)
{
    int rslt;
    this.Invoke((MethodInvoker) delegate
    {
        rslt = ReplaceMessage(msg, key);
    }
    return rslt;
}

事实证明,invoke调用将在它调用的函数中传递异常,而您不能单步执行(调试器中的F11)。我假设它会进入被调用的代码,所以当它失败时,我认为这是实际的调用


我弄乱了一个字符串。函数体中的Format,Invoke将该异常传递给了我,但没有指出问题实际发生在代码中的什么地方。

你能发布使用
键的代码吗。我从未想到“调用”会在函数的其余部分传递错误。但这就是错误所在,事件日志中有一种格式是fubar。谢谢你的邀请。。。这让我看得更远。问题解决了。没问题,我看到的错误主要是
String.Format
调用(跳过索引)。请随意发布您的修复作为接受它的答案。在上面的代码中,我必须将{4}更改为{3}。(以上编辑)我不太熟悉stackoverflow的实际使用,甚至不知道“发布我的修复作为接受它的答案”是什么意思P