代码之家  ›  专栏  ›  技术社区  ›  Maloric

无法将带[]的索引应用于“object”类型的表达式(即使该类型为“dynamic”)

  •  3
  • Maloric  · 技术社区  · 11 年前

    我有一个 ExpandoObject 其创建方式如下:

    public ExpandoObject Get()
    {
        var expando = new ExpandoObject();
        var expandoDic = (IDictionary<string, dynamic>)expando;
    
        // go through the items in the dictionary and copy over the key value pairs)
        foreach (var f in GetFieldList())
        {
            if (f.MaxValues == 1)
            {
                var val = f.Values.Count > 0 ? f.Values[0] : null;
                if (f.displayType == DisplayType.Entity && f.AttachedEntities != null && f.AttachedEntities.Any())
                {
                    if (f.AttachedEntities.Count == 1)
                    {
                        expandoDic.Add(new KeyValuePair<string, dynamic>(f.Code, f.AttachedEntities[0].Get()));
                    }
                    else
                    {
                        expandoDic.Add(new KeyValuePair<string, dynamic>(f.Code, f.AttachedEntities.Select(e => e.Get())));
                    }
                }
                else
                {
                    expandoDic.Add(new KeyValuePair<string, dynamic>(f.Code, GetTypedValue(f.GetValueType(), val)));    
                }
    
            }
            else
            {
                expandoDic.Add(new KeyValuePair<string, dynamic>(f.Code, (dynamic)f.Values.Select(v => GetTypedValue(f.GetValueType(), v))));
            }
        }
        return expando;
    }
    

    这个 GetTypedValue 只需将字符串值转换为适当的类型并返回 dynamic .

    我遇到的问题是,如果我将集合添加到 expandoDic 那么我就不能访问成员而不将其转换为 ICollection 类型考虑以下代码,其中myPage是由上述方法创建的ExpandoObject。

    Response.Write(myPage.menu.items[0]);
    

    菜单属性是一个动态对象 items 。后者是字符串的集合,尽管类型实际上是 IEnumerable<dynamic>'. If I inspect myPage.menu.items, it tells me the type is dynamic{System.Linq.Enumerable.WhereSelectListIterator}`。上述代码产生以下错误:

    Cannot apply indexing with [] to an expression of type 'object'
    

    如果我使用 First() 而不是索引,我得到了以下错误:

    'object' does not contain a definition for 'First'
    

    我知道我可以投 项目 IEnumerable 并立即解决问题,但我正在编写一个开发框架,并希望消除开发人员使用它的任何障碍。

    2 回复  |  直到 11 年前
        1
  •  3
  •   Ramesh Rajendran    11 年前

    对于动态类型,不能在没有转换的情况下使用扩展方法,但可以使用方法的静态调用,而不是:

    var a = yourDynamic.First();
    

    你应该写

    var a = Enumerable.First(yourDynamic);
    
        2
  •  2
  •   Maloric    11 年前

    我解决了我的问题。在创建动态IEnumerable时,我只需要将其转换为数组,如下所示:

    expandoDic.Add(new KeyValuePair<string, dynamic>(f.Code, f.Values.Select(v => GetTypedValue(f.GetValueType(), v)).ToArray()));
    

    这再次证明,必须彻底解释问题往往可以揭示答案。