gpt4 book ai didi

c# - 如何循环遍历泛型类型的列表

转载 作者:行者123 更新时间:2023-12-03 03:05:26 32 4
gpt4 key购买 nike

我需要循环遍历一个列表,其中类型在编译时未知。怎么做?以下代码在运行时失败,不允许转换:

    Type objType = dataObject.GetType();
List<string> strList = new List<string>();

foreach (PropertyInfo prop in objType.GetProperties())
{
var val = prop.GetValue(dataObject);

if (prop.PropertyType.Name.StartsWith("List")) // Is there a better way?
{
foreach (object lval in (List<object>) val) // Runtime failure (conversion not allowed)
{
strList.Add(lval.ToString());
}
}
...

最佳答案

如果您不知道类型,那么:泛型可能不是最佳选择:

IList list = val as IList; // note: non-generic; you could also
// use IEnumerable, but that has some
// edge-cases; IList is more predictable
if(list != null)
{
foreach(object obj in list)
{
strList.Add(obj.ToString());
}
}

关于c# - 如何循环遍历泛型类型的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19811201/

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