【发布时间】:2014-05-09 00:00:55
【问题描述】:
我有一个确实填充的 ListView 控件。问题是它被视为空的。当指定我知道存在的项目的索引时,我收到“ArgumentOutOfRangeException”错误。
public static string folderToUpdate(string folderChanged)
{
Main m = new Main(); // This is the class which this method is in,
// as a side matter I don't even know why I have to create
// an instance of the class I'm ACTUALLY IN
// (but I get a compile time error if I don't).
string folder1 = m.lstFoldersToSync.Items[0].Text;
string folder2 = m.lstFoldersToSync.Items[1].Text;
string folderToUpdate;
// If the folder changed is folder1 then the folder to update must be folder2.
// If the folder changed is folder2 then the folder to update must be folder1.
if (folderChanged == folder1)
{
folderToUpdate = folder2;
}
else
{
folderToUpdate = folder1;
}
return folderToUpdate;
}
错误出现在我声明和定义“folder1”的第 8 行。
一些澄清:我在发布之前进行了广泛的搜索。没有其他问题是完全重复的。有许多类似的问题,但解决方案总是被证明是 empty 列表问题或“Off-by-one 错误”,这些都不是我遇到的问题。我再次强调 Listview 已填充(在表单加载时)。
那会是什么?这个问题会不会和Main m = new Main();有关?
任何帮助将不胜感激。谢谢。
PS:我认为除了第 3、8 和 9 行之外的所有代码都几乎无关紧要(我可能错了)。
编辑:我通过使用包含“lstFoldersToSync”控件内容的静态字段列表解决了这个问题,然后访问它(而不是尝试直接访问控件的内容)。
新的工作代码:
private static List<string> foldersToSync = new List<string>(); // This will be populated with the items in "lstFoldersToSync" control on "Main" form.
public static string folderToUpdate(string folderChanged)
{
// Main m = new Main();
string folder1 = foldersToSync[0];
string folder2 = foldersToSync[1];
string folderToUpdate;
// If the folder changed is folder1 then the folder to update must be folder2.
// If the folder changed is folder2 then the folder to update must be folder1.
if (folderChanged == folder1)
{
folderToUpdate = folder2;
}
else
{
folderToUpdate = folder1;
}
return folderToUpdate;
}
非常感谢所有帮助我的人。
【问题讨论】:
-
你是故意使用静态函数吗?
-
从哪里调用代码?一些事件?粘贴更多代码...
-
@attila 是的,它是静态的,因为我需要从另一个类访问它(而且我不喜欢实例化,我知道它不是最好的)。
-
@ZdravkoDanev 是一个辅助方法,用于确定需要更新哪个文件夹才能匹配另一个(但我认为它无关紧要)。
-
@GrantWinney "非静态字段方法或属性需要对象引用"