【发布时间】:2026-01-09 02:35:01
【问题描述】:
我有一个类,我需要通过对象属性来反映并检查值和其他内容。当我有一个列表并尝试将项目转换为 IEnumerable 时,一切似乎都在工作异常。
if (propType.GetInterfaces().Contains(typeof(IEnumerable)))
{
var value = prop.GetValue(source);
Type underlyingType = propType.GetGenericArguments()[0];
var enumerable = value as IEnumerable<object>;
if(enumerable == null)
{
// problem here......
}
// Check the items in the list
}
propType 返回为:
FullName = "System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
底层类型返回为:
System.Int32
当它是一个自定义类的列表时,这很有效,当它是一个值类型时,它似乎会被破坏。
有人可以帮忙吗?
【问题讨论】:
-
你可以推理出来。访问列表元素需要转换为对象。简单的列表包含引用类型,它们直接继承自object。绝对不是简单的值类型,元素必须是boxed。装箱转换需要代码,但该代码不存在。