如何遍历泛型类型的列表

Ger*_*ard 2 c#

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

    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());
            }
        }
        ...
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

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

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());
    }
}
Run Code Online (Sandbox Code Playgroud)