【发布时间】:2010-11-17 19:54:50
【问题描述】:
以下是我的代码的摘录:
public class AllIntegerIDs
{
public AllIntegerIDs()
{
m_MessageID = 0;
m_MessageType = 0;
m_ClassID = 0;
m_CategoryID = 0;
m_MessageText = null;
}
~AllIntegerIDs()
{
}
public void SetIntegerValues (int messageID, int messagetype,
int classID, int categoryID)
{
this.m_MessageID = messageID;
this.m_MessageType = messagetype;
this.m_ClassID = classID;
this.m_CategoryID = categoryID;
}
public string m_MessageText;
public int m_MessageID;
public int m_MessageType;
public int m_ClassID;
public int m_CategoryID;
}
我正在尝试在我的main() 功能代码中使用以下内容:
List<AllIntegerIDs> integerList = new List<AllIntegerIDs>();
/* some code here that is ised for following assignments*/
{
integerList.Add(new AllIntegerIDs());
index++;
integerList[index].m_MessageID = (int)IntegerIDsSubstring[IntOffset];
integerList[index].m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
integerList[index].m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
integerList[index].m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
integerList[index].m_MessageText = MessageTextSubstring;
}
问题在这里:我正在尝试使用 for 循环打印列表中的所有元素:
for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++) //<----PROBLEM HERE
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", integerList[cnt3].m_MessageID,integerList[cnt3].m_MessageType,integerList[cnt3].m_ClassID,integerList[cnt3].m_CategoryID, integerList[cnt3].m_MessageText);
}
我想找到最后一个元素,以便在我的 for 循环中将 cnt3 等同起来,并打印出 List 中的所有条目。列表中的每个元素都是类AllIntegerIDs 的对象,如上面代码示例中所述。如何找到列表中最后一个有效条目?
我应该使用integerList.Find(integerList[].m_MessageText == null;之类的东西吗?
如果我使用它,它将需要一个范围从 0 到最大值的索引。意味着我将不得不使用另一个我不打算使用的 for 循环。有没有更短/更好的方法?
【问题讨论】:
-
@Viren:我缩进了代码以使其正确显示。如果你在我手下进行了编辑,你能确保我没有撤消它们吗?
-
与您的问题无关,但除非需要,否则您真的不应该实现终结器。
-
与问题无关,但为了可读性和可维护性,我建议您使用
AllIntegerIDs newItem = new AllIntegerID();,使用它来分配所有字段并然后调用integerList.Add(newItem)。或者使用属性而不是字段并使用 C# 3.0 对象初始化器语法。