gpt4 book ai didi

c# - 反射(reflect)一个列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:12 24 4
gpt4 key购买 nike

我正在尝试制作模型反射工具。到目前为止,我已经走了很长一段路,但现在我被困住了。

我有这个

public static void RenderModelList(List<T> modelList)
{
foreach (T model in modelList)
{
PropertyInfo[] properties = model.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
object propValue = property.GetValue(model, null);
//Check if the property is a collection and do recursion
if (propValue != null)
{
if (isCollection(propValue))
{
//This only works for Lists of the same <T>
List<T> li = Convert.ChangeType(propValue, propValue.GetType()) as List<T>;
if (li != null)
{
if (li.Count > 0)
{
RenderModelList(li, loop);
}
}
else
{
//Its another type what to do?
// Create a List<> of unknown type??
}
}
}
}
}
}

我的问题是,如果我将此方法传递给 List<Persons>并且这个人有一个属性是 List<Cars> - 我不能使用 Convert.ChangeType - 因为这不是 T。

那么我如何遍历“列表”并访问该对象的属性呢?

最佳答案

在我看来,您的方法可以更松散地键入:

public static void RenderModelList(IEnumerable list)
{
foreach (object model in list)
{
...
}
}

然后您只需转换为 IEnumerable,而不是特定的序列或列表类型。

关于c# - 反射(reflect)一个列表<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12166767/

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