获取 OrderedDictionary 的值

Get value of an OrderedDictionary

我无法从我的 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 的元素,并且对象存在于值中,但是行 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);

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

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

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

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

然后查看调试器的直接 Window 是否 objectKey.ReferenceEquals(x) returns 对于

中的任何 x 是否为真
ifcList.Keys