获取 OrderedDictionary 的值

问题描述 投票:0回答:1

我无法从我的 OrderedDictionary 中找到值,我正在关注堆栈上的几篇文章,所以我看不到我做得不好?

private List<IfcElement> readListParamFromList(Int32 index, OrderedDictionary ifcList)
{
    List<IfcElement> retour = new List<IfcElement>();
    if (this.ListParams[index] != "")
    {
        string[] listStrings = this.ListParams[index].Split(',');

        foreach (string idString in listStrings)
        {
            long idElt = -1;
            idElt = IfcGlobal.GetIdFromIfcString(idString);
            try
            {
                object objectFound = (IfcElement)ifcList[(object)idElt];
                IfcElement newElt = (IfcElement)objectFound;
                retour.Add(newElt);
                this.addChildren(newElt);
            }
            catch
            {
                this.ErrorFound = true;
                this.ListItemsNotFound.Add(idElt);
            }
        }
    }
    return retour;
}

在这里我发现IdElt=104。然后我检查了调试,我的 OrderedDictionary 内部有一个 Key=104 的元素,并且对象存在于 value 中,但是

object objectFound = (IfcElement)ifcList[(object)idElt];
行始终返回 null。我的语法有问题吗? 也许有帮助,我添加了在字典中添加元素的方式:

public class GroupedListElements
{
    public string Type { get; set; } = "";
    public OrderedDictionary ListIfcElements = new OrderedDictionary();
    public GroupedListElements()
    {

    }
}

GroupedListElements newGroupList = new GroupedListElements { Type = 

newElt.GetType().Name };
newGroupList.ListIfcElements.Add(newElt.ID, newElt);
this.ListGroupped.Add(newGroupList);
c# dictionary ordereddictionary
1个回答
2
投票

我认为问题在于,通过在从有序字典中检索对象之前转换为 (object) ,字典会尝试根据 Object.Equals() 来定位键。如果装箱的长对象具有相同的引用(即 ReferenceEquals 方法返回 true),则 Object.Equals 返回 true。如果您不介意使用字符串而不是长整型作为键,我建议您这样做。

要详细了解代码出了什么问题,可以替换以下行

object objectFound = (IfcElement)ifcList[(object)idElt];

object objectKey = (object)idElt;
object objectFound = (IfcElement)ifcList[objectKey];

然后在调试器的直接窗口中查看 objectKey.ReferenceEquals(x) 是否对任何 x 中的 x 返回 true

ifcList.Keys
© www.soinside.com 2019 - 2024. All rights reserved.