无法转换为对象列表

时间:2017-01-20 15:31:36

标签: c#

我有一个获取属性值或获取嵌套属性值的方法,这部分工作正常,但我想将集合添加到字符串,以防某些属性是一个集合,我似乎有一个问题:

代码:

public static object GetNestedPropValue<TObject>(TObject obj, string propName)
{
    string[] nestedObjectProp = propName.Split('.');
    string[] childProperties = nestedObjectProp.Skip(1).ToArray();

    string parentProp = nestedObjectProp.FirstOrDefault();

    foreach (string property in childProperties)
    {
        if (obj == null)
        {
            return null;
        }

        PropertyInfo info = obj.GetType().GetProperty(parentProp);

        if (info == null)
        {
            return null;
        }

        object nestedObject = info.GetValue(obj);

        if(childProperties.Count() == 1)
        {
            Type checkNestedType = nestedObject.GetType();

            if (IsICollection(checkNestedType) && IsIEnumerable(checkNestedType))
            {
                var nestedObjectValues = nestedObject as List<object>;

                return string.Join(", ", nestedObjectValues
                    .Select(i => i.GetType().GetProperty(childProperties.FirstOrDefault()).GetValue(nestedObject))
                    .ToArray());                   
            }
            return nestedObject.GetType().GetProperty(childProperties.FirstOrDefault()).GetValue(nestedObject);
        }

        GetNestedPropValue(nestedObject, string.Join(".", childProperties.Skip(1)));
    }

    return null;
} 

问题在这里:

var nestedObjectValues = nestedObject as List<object>;

return string.Join(", ", nestedObjectValues
    .Select(i => i.GetType().GetProperty(childProperties.FirstOrDefault()).GetValue(nestedObject))
    .ToArray());   

当我尝试键入对象列表时,它会给我null,这似乎是什么问题?

1 个答案:

答案 0 :(得分:2)

nestedObject根本不是List<object>,因此nestedObject as List<object>会返回null。

作为集合类型并且可枚举当然并不意味着某些T的类型为List<T>。即使这样,List<T>也无法直接转换为List<object>(除了显然T是object)。

我不确定你在这里想要实现什么,但是在尝试将对象转换为松散的猜测类型之前通过反射检查类型对我来说非常奇怪。

相关问题