3

我需要遍历一个在编译时类型未知的列表。怎么做?以下代码在运行时失败,不允许转换:

    Type objType = dataObject.GetType();
    List<string> strList = new List<string>();

    foreach (PropertyInfo prop in objType.GetProperties())
    {
        var val = prop.GetValue(dataObject);

        if (prop.PropertyType.Name.StartsWith("List"))   // Is there a better way?
        {
            foreach (object lval in (List<object>) val)  // Runtime failure (conversion not allowed)
            {
                strList.Add(lval.ToString());
            }
        }
        ...
4

4 回答 4

6

如果您不知道类型,那么 : generics 可能不是最佳选择:

IList list = val as IList; // note: non-generic; you could also
                           // use IEnumerable, but that has some
                           // edge-cases; IList is more predictable
if(list != null)
{
    foreach(object obj in list)
    {
        strList.Add(obj.ToString());
    }
}
于 2013-11-06T11:48:33.307 回答
1

只是想在已经说过的内容中添加一些内容:

您的逻辑有缺陷,因为List<int>(例如)不是List<object>. List<T>在其类型参数中不是协变的。

如果是这样,这样做是合法的:

List<object> listOfObjects = new List<int>();
listOfObjects.Add("a string");

阅读本文以了解有关 C# 中协变/逆变的更多信息:

http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx

于 2013-11-06T12:04:49.010 回答
0
foreach (var propInfo in foobar.GetType().GetProperties())
{
    var val = propInfo.GetValue(foobar, null);

    if (typeof(IEnumerable).IsAssignableFrom(propInfo.PropertyType))
    {
        var collectionItems = (IEnumerable)val;
        if (collectionItems != null)
        {
            foreach (object lval in collectionItems)
            {
                Console.WriteLine(lval);
            }
        }
    }
}
于 2013-11-06T11:54:05.417 回答
0

也许会更容易

 foreach (PropertyInfo prop in objType.GetProperties())
        {
            var val = prop.GetValue(x,null);

            if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) && prop.PropertyType.IsGenericType)   // Is there a better way?
            {
                dynamic dd = val;
                foreach (object lval in dd)  
                {
                    strList.Add(lval.ToString());
                }
            }
于 2013-11-06T12:14:55.543 回答