我有一个ImmutableHashSet<ListItem>
基本项目列表(准确地说来自 System.Collections.Immutable)并尝试调用以下代码
_baseList.Contains(derivedItem)
但这返回false。
即使以下代码行都返回true
object.ReferenceEquals(_baseList.First(), derivedItem)
object.Equals(_baseList.First(), derivedItem)
_baseList.First().GetHashCode() == derivedItem.GetHashCode()
我什至可以编写以下内容并返回 true:
_baseList.OfType<DerivedClass>().Contains(derivedItem)
我做错了什么,我想避免写 .OfType 的东西。
编辑:
private ImmutableHashSet<BaseClass> _baseList;
public class BaseClass
{
}
public class DerivedClass : BaseClass
{
}
public void DoStuff()
{
var items = _baseList.OfType<DerivedClass>().ToList();
foreach (var derivedItem in items)
{
RemoveItem(derivedItem);
}
}
public void RemoveItem(BaseClass derivedItem)
{
if (_baseList.Contains(derivedItem))
{
//doesn't reach this place, since _baseList.Contains(derivedItem) returns false...
_baseList = _baseList.Remove(derivedItem);
}
//object.ReferenceEquals(_baseList.First(), derivedItem) == true
//object.Equals(_baseList.First(), derivedItem) == true
//_baseList.First().GetHashCode() == derivedItem.GetHashCode() == true
//_baseList.OfType<DerivedClass>().Contains(derivedItem) == true
}
编辑2:
这是我的问题的可重现代码,看起来像ImmutableHashSet<>
缓存GetHashCode
并且不会将当前GetHashCode
与列表中的条目进行比较,有没有办法告诉ImmutableHashSet<>
项目GetHashCode
可能不同,至少对于我目前正在检查的项目,因为嘿它该死的相同参考...
namespace ConsoleApplication1
{
class Program
{
private static ImmutableHashSet<BaseClass> _baseList;
static void Main(string[] args)
{
_baseList = ImmutableHashSet.Create<BaseClass>();
_baseList = _baseList.Add(new DerivedClass("B1"));
_baseList = _baseList.Add(new DerivedClass("B2"));
_baseList = _baseList.Add(new DerivedClass("B3"));
_baseList = _baseList.Add(new DerivedClass("B4"));
_baseList = _baseList.Add(new DerivedClass("B5"));
DoStuff();
Console.WriteLine(_baseList.Count); //output is 5 - put it should be 0...
Console.ReadLine();
}
private static void DoStuff()
{
var items = _baseList.OfType<DerivedClass>().ToList();
foreach (var derivedItem in items)
{
derivedItem.BaseString += "Change...";
RemoveItem(derivedItem);
}
}
private static void RemoveItem(BaseClass derivedItem)
{
if (_baseList.Contains(derivedItem))
{
_baseList = _baseList.Remove(derivedItem);
}
}
}
public abstract class BaseClass
{
private string _baseString;
public string BaseString
{
get { return _baseString; }
set { _baseString = value; }
}
public BaseClass(string baseString)
{
_baseString = baseString;
}
public override int GetHashCode()
{
unchecked
{
int hashCode = (_baseString != null ? _baseString.GetHashCode() : 0);
return hashCode;
}
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(string baseString)
: base(baseString)
{
}
}
}
如果我将代码更改为ImmutableHashSet<>
可以ImmutableList<>
正常工作,那么如果你们没有提出任何好主意,我将切换到列表。