我从字典中收到indexOutOfBound错误,所以我在网上搜索,他们说这是线程安全的问题,因为我没有锁定字典,所以我在网上搜索并且不了解如何在字典上使用锁。但是令我惊讶的是,在字典上使用锁之后,代码仍然给出相同的错误。我在字典上实现锁定的方式可能会出错。
c# Dictionary lookup throws "Index was outside the bounds of the array"
我从此链接中学到了锁:--- Correct way to lock the dictionary object
我已经通过类似于我的问题的链接,但是解决方案并不令人满意:C# Dictionary Index was outside the bounds of the array with lock
public class Pattern
{
public int index { get; set; }
public char character { get; set; }
public Pattern(int index, char character)
{
this.index = index;
this.character = character;
}
}
class Solution4
{
public String convert(String s, int numRows)
{
int stringLength = s.Length;
string main = string.Empty;
int counter = 1;
int index = 1;
bool Mode = true;
Dictionary<int, Pattern> dict = new Dictionary<int, Pattern>();
while (stringLength > 0)
{
lock (dict)
{
dict.Add(index, new Pattern(counter, s[index]));
}
if (Mode == true)
{
counter++;
}
else
{
counter--;
}
index++;
if (counter == numRows)
{
Mode = false;
}
else if (counter == 1)
{
Mode = true;
}
stringLength--;
}
for (int i = 1; i <= 5; i++)
{
lock (dict)
{
foreach (var item in dict)
{
if (item.Value.index == i)
{
main += item.Value.character;
}
}
}
}
return main;
}
}
如果您发现我的错误或我做错了什么,我将为您提供很大的帮助。 预先感谢