反射:将反射类型转换为泛型,类型为字符串并对其进行迭代

Reflection: casting reflected type to generic with type as string and iterating over it

我搜索了 Whosebug 并发现了多个相关问题,但 none 回答了它 'completely'。我的理解可能有误,但想检查一下 -

我有一个class

public class Foo
{
     public List<Bar> Bars = new List<Bar>();
}

public class Bar
{
}

由于发生了一些疯狂的反射,此列表仅作为对象传递 -

Foo f = new Foo();
object o = f;
CheckItem(o, "Bars");

// CheckItem has no clue about Bar class and is thus passed the 'Bars' Field name 
public void CheckItem(Object obj, string fieldName)
{
    var value = obj.GetType().GetField(fieldName).GetValue(obj); // returns f.Bars into value as object

    foreach (var bar in value.Bars) // won't compile as value is type object
}

所以,我使用 MakeGenericType 和 Activator.CreateInstance magic

var genericClass = typeof(List<>).MakeGenericType(new[] {value.GetType().FieldType.GetGenericArguments()[0]}); // makes a generic of type List<Bar>
var o = Activator.CreateInstance(genericClass); // o is again of type object
foreach (var bar in o.Bars) // will fail again

SO - 如何调用 foreach 循环来遍历成员。我在 MakeGenericType 周围看到的每个示例都以创建对象 o 结束,none 讨论如何访问其成员,尤其是在上面的 foreach 循环中。

感谢任何意见。

谢谢

如果您不需要知道元素类型,您需要做的就是转换为 IEnumerable:

var sequence = (IEnumerable) value;
foreach (var item in sequence)
{
    // The type of the item variable is just object,
    // but each value will be a reference to a Bar
}

(顺便说一句,我强烈建议改用私有字段并公开属性 - 但那是另一回事。)