简体   繁体   English

Delphi-> Delphi棱镜,如何使用记录数组?

[英]Delphi -> Delphi prism, how to use array of records?

I'm learning Delphi Prism, and i don't find how to write the following code with it : 我正在学习Delphi Prism,但找不到如何用它编写以下代码:

type
  TRapportItem = record
   Label : String;
   Value : Int16;
   AnomalieComment : String;
  end;

type 
  TRapportCategorie = record
    Label : String;
    CategoriesItems : Array of TRapportItem;
  end;

type 
  TRapportContent = record
    Categories : array of TRapportCategorie;
  end;

Then, somewhere, i try to put items in the array : 然后,在某个地方,我尝试将项目放入数组中:

rapport.Categories[i].Label:=l.Item(i).InnerText;

But it doesn't work.. Can someone enlight me? 但这不起作用。有人可以启发我吗?

Thanks! 谢谢!

  • You didn't specify exactly what "didn't work". 您没有确切指定什么“无效”。 You should include the error in questions like this. 您应该在此类问题中包含错误。
  • Arrays are reference types, and they start out with the value nil . 数组是引用类型,它们以值nil开头。 They need to be initialized before elements can be accessed. 需要先初始化它们,然后才能访问元素。

You can do this with the new operator: 您可以使用new运算符执行此操作:

rapport.Categories = new TRapportCategorie[10]; // 0..9
  • Arrays are quite a low-level type. 数组是很底层的类型。 Usually it's better to work with List<T> instead. 通常,最好使用List<T>代替。

So you'd declare: 因此,您需要声明:

Categories: List<TRapportCategorie>;
  • But lists also need initializing, using the new operator. 但是列表也需要使用new运算符进行初始化。 Also, modifying the return value of the indexer on a list containing a value type will be modifying a copy, not the original, which leads to the next point. 同样,在包含值类型的列表上修改索引器的返回值将修改副本,而不是原始副本,从而导致下一个问题。
  • Records are usually not the best data type for representing data, as they are not reference types; 记录通常不是代表数据的最佳数据类型,因为它们不是引用类型。 it's very easy to end up modifying a copy of the data, rather than the original data. 最终修改数据的副本而不是原始数据非常容易。 It's usually best to use classes instead, where you can put all the initialization code (such as allocating the array or list) in the constructor. 通常最好改用类,您可以在其中将所有初始化代码(例如分配数组或列表)放入构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM