【发布时间】:2020-07-28 08:14:36
【问题描述】:
我正在尝试从内存流中读取文件并将其内容组织到实例列表中。文件中的某些行具有相应的类的某些类型,并且文件中可以出现多个相同类型的行。
我当前的代码如下所示:
public void initializeStructure( System.IO.MemoryStream RawFile )
{
int positioninFile = 0;
while (!reachedEndOfFile)
{
string recordType = GetRecordType(RawFile, positioninFile);
int ListPosition = MessageStructure.Count;
switch (recordType)
{
case "01":
Class_01 _01 = new Class_01(Params);
MessageStructure.Add(_01);
break;
case "02":
Class_02 _02 = new Class_02(Params);
MessageStructure.Add(_02);
break;
case "04":
Class_04 _04 = new Class_04(Params);
MessageStructure.Add(_04);
break;
default:
reachedEndOfFile = true;
break;
}
string row = GetRowFromMemoryStream(RawFile, 572, positioninFile);
MessageStructure[ListPosition].WriteRule(row);
ListPosition++;
positioninFile += 572;
}
}
消息结构定义:
public List<A_Record> MessageStructure = new List<A_Record>();
这些类的外观示例:
public class Class_01 : A_Record
{
public Class_01( Dictionary<string, A_AbstractClass> Params ) : base(Params)
{
RecordType = "01";
RecordTitle = "Name of record";
}
}
A_Record 摘要
public abstract class A_Record
{
public virtual string RecordType { get; set; }
public virtual string RecordTitle { get; set; }
public int RecordLength { get; set; }
public void WriteRule( string Vektis_Rule )
{
int writePosition = 0;
foreach ( KeyValuePair<string, A_Element> Element in Elementen )
{
string ElementValue = Vektis_Rule.Substring( writePosition, Element.Value.Length );
Element.Value.Write( ElementValue );
writePosition += Element.Value.Length;
}
}
public A_Record(Dictionary<string, A_Gegevenselement> Volgnummers)
{
Elementen = Volgnummers;
RecordLength = 0;
foreach (KeyValuePair<string, A_Gegevenselement> Element in Elementen)
{
var currentElement = Elementen[Element.Key];
currentElement.StartingPosition = RecordLength;
RecordLength += currentElement.Length;
}
}
}
所以基本上,对于出现的每个“04”行,我想将一个新的 Class_04 实例添加到列表中,然后将该行的内容写入实例。
很遗憾,这并没有像我希望的那样工作。如果我将 Class_04 的多个实例添加到列表中,它们都具有添加的最后一个 Class_04 行的值。这可能意味着 List 中的所有 Class_04 条目都是同一个实例,并且我不断地覆盖它而不是添加一个新实例。但是我不明白这是怎么回事,因为看起来我每次都在 While 循环中创建一个新实例。
有人可以帮助我吗?如您所知,直到最近我才使用 PHP、Python 和 Javascript。所以我可能只是在这里度过了一个d'oh的时刻,却错过了一些非常明显的东西。
提前感谢您的时间和精力!
【问题讨论】:
-
嘿,欢迎,是的,你是对的,你每次都创建一个新实例,以避免在循环之前声明实例,如
Class_01 _01 = null;然后检查_01 == null是否启动它通过调用 new,如果不添加_01到您的列表中 -
MessageStructure 的定义是什么 你正在给它添加不同的类型。
-
是的,您正在创建类的新实例并将其添加到列表中。问题必须出在传递给类的参数上,或者出在类的定义上。你能把这些给我们看吗?
-
你可以写
MessageStructure.Add(new Class_01(Params));,因为你从不使用任何地方引用的类。另外:您在每个 while 循环中都用int ListPosition = MessageStructure.Count;覆盖ListPosition++;- 冗余,但不是该行为的来源。 -
MessageStructure 的定义是
public List<A_Record> MessageStructure = new List<A_Record>();。添加到列表中的所有类都是抽象 A_Record 的扩展。好点,我会把这个添加到问题中