gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:44:56 24 4
gpt4 key购买 nike

我搜索了 StackOverflow 并发现了多个相关问题,但没有一个能“完全”回答它。我的理解可能有误,但想检查一下 -

我有课

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 魔法

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 结束,没有一个讨论如何访问其成员,尤其是在上面的 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
}

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

关于c# - 反射:将反射类型转换为泛型,类型为字符串并对其进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28753325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com