参数计数与调用不匹配? [英] Parameter count mismatch with Invoke?

查看:15
本文介绍了参数计数与调用不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码块导致错误:TargetParameterCountException is unhandled by user code.参数计数不匹配.

The code block below results in the error: TargetParameterCountException was unhandled by user code. Parameter count mismatch.

    public void AddListViewItem(string[] Data)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<string[]>(AddListViewItem), Data);
        }
        else
        {
            ListViewData.Items.Add(Data[0]).SubItems.AddRange
            (
                new string[]
                { 
                    Data[1],
                    Data[2],
                    Data[3],
                }
            );
        }
    }

有什么想法吗?

推荐答案

由于数组协方差导致的错误;一个字符串数组可分配给 object[].这会导致 Invoke 方法将 string 数组的每个元素视为应该是 AddListViewItem 方法的参数.

The error occurs because of array covariance; an array of strings is assignable to object[]. This causes the Invoke method to treat each element of the string array as if it should be an argument to the AddListViewItem method.

这里有一个修复:

Invoke(new Action<string[]>(AddListViewItem), new object[] {Data});

(或)

Invoke(new Action<string[]>(AddListViewItem), (object)Data);

这让 Invoke 清楚地知道目标方法采用 single 参数.

This makes it crystal-clear to Invoke that the target method takes a single parameter.

这篇关于参数计数与调用不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆