[原创]调用IList.Remove 方法失效(解决方案)

Removes the first occurrence of a specific object from the IList.

方案一
This method determines equality using the default comparer Comparer<(Of <(T>)>).Default. Comparer<(Of <(T>)>).Default checks whether type T implements System.IComparable<(Of <(T>)>) and uses that implementation, if available. If not, Comparer<(Of <(T>)>).Default checks whether type T implements System.IComparable. If type T does not implement either interface, this method uses Object.Equals.

This method is an O(n) operation, where n is Count.

其实备注中已经给我指明了解决方案."this method uses Object.Equals"

所以我们重写Object.Equals方法即可.
 

  class DemoList
    
{
        
private string _s;
        
public DemoList() { }
        
public DemoList(string _s)
        
{
            
this._s = _s;
        }

        
public string s
        
{
            
get return _s; }
            
set { _s = value; }
        }

        
public override bool Equals(object obj)
        
{     
            
if (this.s == ((DemoList)obj).s)
            
{
                
return true;
            }

            
else
            
{
                
return false;
            }
         
        }

    }

方案二(来源)
http://msdn2.microsoft.com/zh-cn/library/system.collections.ilist.remove(VS.85).aspx
class SimpleList : IList
{
    
private object[] _contents = new object[8];
    
private int _count;

    
public SimpleList()
    
{
        _count 
= 0;
    }


    
// IList Members
    public int Add(object value)
    
{
        
if (_count < _contents.Length)
        
{
            _contents[_count] 
= value;
            _count
++;

            
return (_count - 1);
        }

        
else
        
{
            
return -1;
        }

    }


    
public int IndexOf(object value)
    
{
        
int itemIndex = -1;
        
for (int i = 0; i < Count; i++)
        
{
            
if (_contents[i] == value)
            
{
                itemIndex 
= i;
                
break;
            }

        }

        
return itemIndex;
    }


    
public void Remove(object value)
    
{
        RemoveAt(IndexOf(value));
    }

    
public int Count
    
{
        
get
        
{
            
return _count;
        }

    }

    
public object this[int index]
    
{
        
get
        
{
            
return _contents[index];
        }

        
set
        
{
            _contents[index] 
= value;
        }

    }
 
    
public void Clear()
    
{
        _count 
= 0;
    }
 
   
  }
 

posted @ 2008-01-19 22:28  E.L.---黑者如斯夫,不舍昼夜......  阅读(893)  评论(0编辑  收藏  举报