如何在c#中传递结构数组给类

本文关键字:结构 数组 | 更新日期: 2023-09-27 18:12:20

总之,我很难将struct传递给类构造函数。我是在多线程过程中的一个现有代码的一部分。在一个类中定义了以下结构:

SchemaFileRec[] m_TableList;
struct SchemaFileRec
{
    public ArrayList  saFile;
    public ArrayList  saImpTab;
    public ArrayList  saSheet;
    // And others...
    public int[]      nColHead;
    public int[]      nSkipBeg;
    public int[]      nSkipEnd;
    public string     strADTFld;
};

在一个方法(称为ExecCmd的旧方法)中使用它来做一些处理。我将这个方法重写为一个类;实际上是BackgroundWorker的一个子类。从本质上讲,我正在采用一种方法来处理一些"长时间运行"的任务,并将其多线程化。我:

public class ExecCmdsThredded : BackgroundWorker 
{
    // Global variables and constants.
    private int nTable;
    private List<int> kPrmArray = null;
    private List<object> StructureArray = null;
    private SpreadsheetGear.IWorksheet worksheet;
    // Default constructor to handle thred properties.
    public ExecCmdsThredded()
    {
        WorkerReportsProgress = true;
        WorkerSupportsCancellation = true;
    }
    // Constructor to parse relevant parameters to worker.
    // Or as an array of objects public ExecCmdsThredded(object[] _StructArr, etc. 
    public ExecCmdsThredded(List<object> _StructArr, List<int> _kPrmArr, ArrayList[] _saCmd, 
                            int _nTable, SpreadsheetGear.IWorksheet _worksheet) : this()
    {
        this.nTable = _nTable;
        this.kPrmArray = _kPrmArr;
        this.StructureArray = _StructArr;
        this.worksheet = _worksheet;
    } 
    // ...

我现在想通过构造函数将结构从上面传递到ExecCmdsThredded类,但我以前从未这样做过,我不确定是否有可能以我想要的方式做到这一点?我可以显式地传递struct的每个组件,但我想避免这种情况。

感谢您的宝贵时间。

如何在c#中传递结构数组给类

你总是可以传递一个对象数组object[],在里面你可以装箱任何类型的结构体或类,不建议这样做,因为装箱/拆箱的副作用。我的意思是:

new ExecCmdsThredded(new object[] { new SchemaFileRec(), new AnotherSchema() });

但我建议放弃结构,创建类,以便您可以使用Generics来代替,至少使代码更具可读性。

每当我开始传递结构时,我都会感到不舒服。当你有一个想要作为参数传递的结构体集合时,请仔细地重新审视设计……"我为什么要使用结构体?"我建议在大多数情况下将结构转换为类。

有几个链接可以帮助您决定是使用结构体还是类。搜索StackOverflow和MSDN