簡體   English   中英

錯誤:System.ArgumentOutOfRangeException:索引超出范圍。 必須為非負數且小於集合的大小

[英]Error: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection

我在以下代碼中遇到一個異常:“索引超出范圍。必須為非負數,並且小於集合的大小。”代碼中實際上是怎么回事,處理了一些重復的值,這些值最終被占用數據網格

try
         {
            int index = alerts.Find(alertName);
            if (index >= 0 && tblAlarm.Rows.Count > idx)
            {
               DataRow row = tblAlarm.Rows[idx];
               m_dcDuplicates.ReadOnly = false;

            }
         }

我需要將int等類型的大小增加到long嗎? 還是需要任何其他簽入代碼?

由於您使用的是lock語句,因此大概是多線程實現。

可能的原因是您無法正確同步對對象的訪問。 再看那將更新集合任何其他代碼( this在上面的代碼) -如果這個問題並不明顯張貼。

更新

例如,在更新的源代碼中,索引器的設置器未同步:

public Alert this[int index]
{
    get ...
    set
    {
        this.List[index] = value;
    }
}

您可能需要以下內容:

public Alert this[int index]
{
    get ...
    set
    {
        lock(this)
        {    
            this.List[index] = value;
        }
    }
}

代碼中的另一個奇怪之處是AddRemove方法引用this.InnerList ,而索引器引用this.List

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM