我的Backgroundworker从路径中检索和计算,我需要返回一个字符串数组和一个double数组。如何将它们打包在一起? 我知道返回的结果是这样的:
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
int result = 2+2;
e.Result = result;
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
int result = (int)e.Result;
MessageBox.Show("Result received: " + result.ToString());
}
我也尝试使用元组,但我的软件无法识别,我使用的是C#2008快递版。
如何将两种不同类型的阵列组合在一起?
答案 0 :(得分:4)
创建数据传输类型。例如:
class MyResult //Name the classes and properties accordingly
{
public string[] Strings {get; set;}
public double[] Doubles {get; set;}
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
//Do work..
e.Result = new MyResult {Strings =..., Doubles = ... };
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MyResult result = (MyResult)e.Result;
//Do whatever with result
}
答案 1 :(得分:1)
创建自定义类并将其传递给结果。
public class MyClass
{
public MyClass(string[] strings, double[] doubles)
{
this.Strings = strings;
this.Doubles = doubles;
}
public string[] Strings {get;set;}
public double[] Doubles {get;set;}
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
MyClass result = new MyClass(new string[] {"a", "b"}, new double[] {1d, 2d});
e.Result = result;
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MyClass result = (MyClass)e.Result;
// process further
}
答案 2 :(得分:1)
创建专门用于保存结果的类。
public class BackgroundWorkResult
{
public List<string> StringList {get;set;}
public List<int> IntList {get;set;}
}
在分配e.Result = new BackgroundWorkResult() { ... };
通常最好为每种后台工作者创建一个类(对于Event Hanlders)。这样,如果在下一版本的代码中需要从BackgroundWorker返回的其他信息,则只需在结果类中添加属性即可。