【问题标题】:getting the elements of a Collections.Generic through refllection通过反射获取 Collections.Generic 的元素
【发布时间】:2013-09-18 00:46:07
【问题描述】:

我目前正在研究一个给定根对象链接的类,并获取该类指向的所有内容,然后创建一个打印输出,以便可以对其进行过滤和搜索以找到类似的内容空指针,以及引用同一个对象的多个事物。

我已经能够通过使用 LINQ 和反射来完成大部分工作,除了能够查看列表或字典的元素。

使用反射我可以得到它是typeof(List<"someClass">),或 typeof(Dictionary)。这件事听起来可能微不足道(因为列表包含的类型应该是已知的),但在当前基准程序的许多地方都有任意数量的列表和字典,它们可能包含程序集中的几乎任何类对象。

问题是:我将如何从存储的 FieldInfo 中进行测试,以发现它具有这些 Collections.Generic 之一的类型,然后使用反射获取集合的元素,以便我可以获得 FieldInfo元素?

编辑代码

// behave is a pointer to a System.object
// infoList is a List<fieldInfo> that belong to behave
string DisplayFields(){
    string _str = "";
    List<FieldInfo> _newList = infoList; 
    if(_newList != null && _newList.count > 0){
        foreach(FieldInfo info in _newList){
            if(info.FieldType.ToString().Contains(".List")){
                _str += "\t" + info.Name;
                _str += ".typeof(" + info.FieldType + "): ";
                _str += ((info.GetValue(behave)!=null)?info.GetValue(behave):"null");
                _str += "\n";
                // this is where the work on List should happen
            }else if(info.FieldType.ToString().Contains(".Dictionary")){
                _str += "\t" + info.Name;
                _str += ".typeof(" + info.FieldType + "): ";
                _str += ((info.GetValue(behave)!=null)?info.GetValue(behave):"null");
                _str += "\n";
                // this is where the work on Dictionary should happen
            }else if(info.FieldType.ToString().Contains("String")){
                _str += "\t" + info.Name;
                _str += ".typeof(" + info.FieldType + "): ";
                _str += ((info.GetValue(behave)!=null)?info.GetValue(behave):"null");
                _str += "\n";
            }else{
                _str += "\t" + info.Name;
                _str += ".typeof(" + info.FieldType + "): ";
                _str += ((info.GetValue(behave)!=null)?info.GetValue(behave):"null");
                _str += "\n";
            }
        }
    }
    return _str;
}

【问题讨论】:

  • 老兄,不要试图重新发明轮子,使用 LINQ
  • @HighCore 你能举个例子来说明你的意思吗,或者给我指点什么来说明你的意思?
  • 发布一些你想要实现的代码。另外,你为什么不直接list.OfType&lt;YourType&gt;()?我不明白你想做什么。
  • 天哪,这到底是什么东西?你想毁灭地球吗?你为什么要做埃及牙套?
  • 大括号样式,代码格式与题无关。问题是我如何有效地获取 Collections.Generic 集合的元素

标签: c# linq reflection mono


【解决方案1】:

这适用于大多数收藏。也许它会为你工作。

    object fieldValue = fieldInfo.GetValue( obj );

    if ( fieldValue is IEnumerable )
      {
      foreach ( var item in (IEnumerable)fieldValue )
        {
        //do your stuff
        Console.WriteLine(item.GetType());
        Console.WriteLine(item);
        }
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多