1 泛型类
public class DataItem<Type1, Type2>
{
public Type1 Text
{
get;
set;
} public Type2 Value
{
get;
set;
}
}
2 list
List<DataItem<string, int>> list = new List<DataItem<string, int>>();//定义 list.Add(new DataItem<string, int> { Text = "采购", Value = 1 });//添加
list.Remove(new DataItem<string, int> { Text = "采购", Value = 1 });
// 无法删除
该怎么样删除呢?不用list.RemoveAt[0],不用索引
public class DataItem<Type1, Type2>
{
public Type1 Text
{
get;
set;
} public Type2 Value
{
get;
set;
}
}
2 list
List<DataItem<string, int>> list = new List<DataItem<string, int>>();//定义 list.Add(new DataItem<string, int> { Text = "采购", Value = 1 });//添加
list.Remove(new DataItem<string, int> { Text = "采购", Value = 1 });
// 无法删除
该怎么样删除呢?不用list.RemoveAt[0],不用索引
但是我还是想知道list.Remove()怎么用,而为啥不能删除?
public class DataItem<Type1, Type2>
{
public Type1 Text
{
get;
set;
} public Type2 Value
{
get;
set;
}
public override bool Equals(object obj)
{
DataItem<Type1, Type2> other = obj as DataItem<Type1, Type2>;
if (other == null)
{
return false;
}
return Object.Equals(this.Text, other.Text) && Object.Equals(this.Value, other.Value);
}
}重写下Equals
public bool Remove(T item)
{
int num = this.IndexOf(item);
if (num >= 0)
{
this.RemoveAt(num);
return true;
}
return false;
}
它是先找到索引,然后再按索引删除的。
所以应该看IndexOf方法;
public int IndexOf(T item)
{
return Array.IndexOf<T>(this._items, item, 0, this._size);
}
进一步Array.IndexOf<T>
public static int IndexOf<T>(T[] array, T value, int startIndex, int count)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (startIndex < 0 || startIndex > array.Length)
{
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (count < 0 || count > array.Length - startIndex)
{
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
}
return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
}
再进一步EqualityComparer<T>.Default.IndexOf
internal virtual int IndexOf(T[] array, T value, int startIndex, int count)
{
int num = startIndex + count;
for (int i = startIndex; i < num; i++)
{
if (this.Equals(array[i], value))
{
return i;
}
}
return -1;
}
再深入没找到了,这个this.Equals是个抽象方法。不过内部肯定是调用类型T的Equals(没重写则调用Object的,Object的默认Equals比较的是引用,而不是具体的属性值,所以你第一个添加的那个对象和你移除的那个不是同一引用,故返回false,就没找到元素,也就没有移除)来比较相等。重写之后就会按照比较属性值而不是引用了.再优化一下
public override bool Equals(object obj)
{
DataItem<Type1, Type2> other = obj as DataItem<Type1, Type2>;
if (other == null)
{
return false;
}
if (Object.ReferenceEquals(this, other))
{
return true;
}
return Object.Equals(this.Text, other.Text) && Object.Equals(this.Value, other.Value);
}
或者
ILSPY