简体   繁体   English

将未知类型的列表转换为通用列表类型

[英]Casting a list of an unknown type to a generic list type

I'm processing a lot of FieldInfo information and I want to add exceptions for certain types of data to process them differently (To make a neat output string) but I can't find a way to cast the object to a List so I can get the count from it. 我正在处理大量FieldInfo信息,并且想为某些类型的数据添加异常以进行不同的处理(以生成整洁的输出字符串),但是我找不到将对象转换为List的方法,因此我可以从中得到计数。

My code: 我的代码:

string str = "";
string value = "";

foreach (FieldInfo fieldInfo in fieldInfos)
{
    if (fieldInfo.Name == "Sprite" || fieldInfo.Name == "Background")
    {
        value = "Unreadable";
    }
    else if (fieldInfo.GetValue(type) == null)
    {
        value = "Null";
    }
    else
    {
        switch (fieldInfo.GetValue(type).GetType().Name)
        {
            default:
                value = fieldInfo.GetValue(type).ToString();
                break;
            case "Color":
                value = ((Color)fieldInfo.GetValue(type)).Name;
                break;
            case "List`1":
                value = (((System.Collections.Generic.List<>)fieldInfo.GetValue(type)).Count - 1).ToString();
                break;
        }
    }

    str += "        " + fieldInfo.Name + ": " + value + Environment.NewLine;
}
return str;

Cast it to non-generic ICollection instead: 而是将其强制转换为非通用ICollection

(((System.Collections.ICollection)fieldInfo.GetValue(type)).Count - 1).ToString();

It will give you access to Count property. 它将使您可以访问Count属性。

If you're just after the number of items then just use the non-generic IList which List<> also implements: 如果您只是在数量之后,那么只需使用List<>也实现的非通用IList

case "List`1":
  value = (((System.Collections.IList)fieldInfo.GetValue(type)).Count - 1).ToString();
  break;

You could add some flexibility by supporting any container by changing the default clause to this: 您可以通过将default子句更改为此来支持任何容器,从而增加一些灵活性:

default:
 if (typeof(System.Collections.ICollection).IsAssignableFrom(fieldInfo.GetValue(type).GetType())
   value = (((System.Collections.ICollection)fieldInfo.GetValue(type)).Count - 1).ToString();
  else
    value = fieldInfo.GetValue(type).ToString();
  break;

Now you'll handle collections such as Dictionary<> and LinkedList<> as well as List<> 现在,您将处理Dictionary<>LinkedList<>以及List<>这样的集合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM