2014-01-23 76 views
0

我尝试从其他线程更改ListView。我得到一个错误:“System.String类型的对象不能转换为类型System.String []”。如果我不传递string []作为参数,则编译器不会编译代码。你有什么想法可能是错的?无法调用方法

public delegate void UpdateListView(string[] request); 
public void UpdateComponents(string[] request) 
{ 
    for (int j = 0; j < request.Length; j++) 
    { 
     switch (request[j]) 
     { 
      case "ListViewSubnetworksChanged": 
       if (listView1.InvokeRequired) 
       { 
        UpdateListView d = new UpdateListView(UpdateComponents); 
        this.Invoke(d, request); 
       } 
       else 
       { 
        listView1.Items.Clear(); 
       } 
       break; 
     } 
    } 
} 

回答

0

该方法是要求一个数组,所以你不能传递一个字符串。如果你只有一个字符串,你可以这样创建一个包含一个字符串的新数组并调用方法:

string val = "Data"; 
string[] arrayVal = new string[] { val }; 
UpdateComponents(arrayVal); 

或者将其简化为一条线:

UpdateComponents(new string[] { val }); 
0

这没有什么错。 编译器得到你的语法错误,因为你试图给字符串作为参数而Invoke()需要的参数是字符串[] 你应该给指出正确的格式的数据。 您可以使用STRING。 ToArray的()聚合函数字符串转换为字符串[]

顺便说一句,使用的foreach循环上,而不是在要遍历一个集合的数据,这些情况。

0

回顾你的问题和代码,我不明白你为什么会在第一时间进行递归调用。我想如下简化代码:

private void UpdateComponents(string[] request) 
{ 
    for (int j = 0; j < request.Length; j++) 
    { 
     switch (request[j]) 
     { 
      case "ListViewSubnetworksChanged": 
       ClearListViewItemsSafe(); 
       break; 
     } 
    } 
} 

private void ClearListViewItemsSafe() 
{ 
    if (listView1.InvokeRequired) 
    { 
     this.Invoke(new Action(() => listView1.Items.Clear())); 
    } 
    else 
    { 
     listView1.Items.Clear(); 
    } 
} 

此外,该代码块假设你确实有其他case条件正在检查,而你在与其他case阻止某些使用了j。如果这两者都不是真的,我会建议进一步优化块:

private void UpdateComponents(string[] request) 
{ 
    foreach (string r in request) 
    { 
     if (r == "ListViewSubnetworksChanged") 
     { 
      ClearListViewItemsSafe(); 
      return; 
     } 
    } 
}