如何将字符串和 DataTable 传递给后台工作者 C# WinForms

How can I pass a string and a DataTable to a backgroundworker C# WinForms

我有一个 WinForm,用户可以 select 一些选项,然后单击一个按钮。该按钮从屏幕上读取用户选项并确定要使用的数据库连接字符串。我想将连接字符串和一个空的 DataTable 传递给另一个 class 中的后台工作人员。然后后台工作人员将连接到数据库,检索数据和 return 数据表以绑定到主窗体上的数据网格。

除了能够传递 DataTable 之外,我已经完成了所有工作。

所以,我的问题是有没有办法将两种不同的数据类型传递给 BGW?或者是否可以将字符串和数据表包装到一个对象中?

Is it possible to wrap the string and datatable into a single object?

如果你需要将两个对象作为一个对象传递,你可以创建一个 class 并且......等等,我们有元组。只需创建一个包含您需要的两个项目的元组并传递它。

您可以使用 System.Tuple, more precisely System.Tuple<T1, T2>, which is a class with two generic properties Item1Item2

Tuple:

var tuple = Tuple.Create(connectionString, dataTable);

使用 System.ValueTuple, or more precisely System.ValueTuple<T1, T2> which is a struct with two generic fields Item1 and Item2, will also work (although it would be boxed).

ValueTuple:

var tuple = (connectionString, dataTable);

另见 Named and unnamed tuples


is there a way to pass two different data types to a BGW

DoWork is not limited to the object you pass in RunWorkerAsync. It could read fields of the type where it is declared. Or, if it is a lambda expression, it can also use local variables from the context (see What are 'closures' in .NET?) 的事件处理程序。