因此,当输入的代码与产品代码匹配时,我正在尝试编写一个按钮以清除数组。但是,当我尝试运行程序时,这个错误(索引超出了数组的范围)不断弹出。这是我使用的代码:
string code;
code = txtcode.Text;
for (int i = 0; i < compartmentno.Length; i++)
{
if (productcode[i] == code)
{
Array.Clear(compartmentno, i, compartmentno.Length);
Array.Clear(productcode, i, productcode.Length);
Array.Clear(name, i, name.Length);
Array.Clear(weight, i, weight.Length);
Array.Clear(address, i, address.Length);
Array.Clear(status, i, status.Length);
}
知道我做错了什么吗?在此先感谢您的帮助!
答案 0 :(得分:3)
因为第三个参数表示要清除的元素数,所以传递整个数组的大小。
您只需要Array.Clear(compartmentno, i, 1)
,因为似乎,您希望清除一个元素。如果您能够详细解释这段代码应该做什么,将会很有帮助。
此外,不要使用六个关联的数组,而是考虑创建一个类来存储您的信息:
class ProductInfo
{
public string CopmartmentNo { get; set; }
public string ProductCode { get; set; }
public string Name { get; set; }
public decimal Weight { get; set; }
public string Address { get; set; }
public int Status { get; set; }
}
答案 1 :(得分:0)
Array.Clear
尝试从一个索引中清除 length 的数组。从0开始使用时没有问题。但是,当您从1开始时,您将超过阵列的末尾。
答案 2 :(得分:0)
您只是将迭代器i
与compartmentno
数组的大小进行比较,if
数组的大小可能与其他数组的大小不同。清除前请使用if(i < ___.Length) Array.Clear(___, i, ___.Length);
语句进行检查。
i
此外,Array.Clear
方法声明第一个参数是起始索引,第二个参数是元素数量toclear,不结束索引。因此,只要0
大于___.Length - i
,此代码就会失败。请改用if(i < ___.Length) Array.Clear(___, i, ___.Length - i);
来减少该值并防止该越界 -
for (int i = 0; i < compartmentno.Length; i++)
{
if (productcode[i] == code)
{
if(i < compartmentno.Length) Array.Clear(compartmentno, i, compartmentno.Length - i);
if(i < productcode.Length) Array.Clear(productcode, i, productcode.Length - i);
if(i < name.Length) Array.Clear(name, i, name.Length - i);
if(i < wight.Length) Array.Clear(weight, i, weight.Length - i);
if(i < address.Length) Array.Clear(address, i, address.Length - i);
if(i < status.Length) Array.Clear(status, i, status.Length - i);
}
因此:
{{1}}