You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何转换因访问级别限制无法访问的类型的列表?

解决私有嵌套类型List无法转换为List的问题

问题原因

直接将List<NestedPrivateType>强制转换为List<object>会失败,核心原因是**List<T>本身不支持协变**。虽然IEnumerable<out T>是协变接口(仅适用于引用类型),但List<T>没有实现协变的隐式转换逻辑,所以强制类型转换会抛出InvalidCastException。

解决方案

以下是几种可行的处理方式:

方法1:利用协变接口间接转换(适用于引用类型)

如果私有嵌套类型是引用类型,可先将列表转为非泛型IEnumerable,再统一转换元素类型:

object listObj = typeof(PublicType).GetField("_theList", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(publicTypeObj);
// 先转非泛型IEnumerable,再转换元素并生成List<object>
List<object> theList = ((IEnumerable)listObj).Cast<object>().ToList();

方法2:通过反射遍历列表元素(通用方案)

无论私有类型是引用类型还是值类型,都可以通过反射调用列表的枚举器来遍历元素:

object listObj = typeof(PublicType).GetField("_theList", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(publicTypeObj);
Type listType = listObj.GetType();

// 获取并调用GetEnumerator方法
MethodInfo getEnumeratorMethod = listType.GetMethod("GetEnumerator", BindingFlags.Public | BindingFlags.Instance);
IEnumerator enumerator = (IEnumerator)getEnumeratorMethod.Invoke(listObj, null);

List<object> theList = new List<object>();
while (enumerator.MoveNext())
{
    theList.Add(enumerator.Current);
}

方法3:通过反射访问索引器遍历

也可以直接借助列表的Count属性和索引器来逐个取出元素:

object listObj = typeof(PublicType).GetField("_theList", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(publicTypeObj);
Type listType = listObj.GetType();

// 获取列表元素总数
PropertyInfo countProp = listType.GetProperty("Count", BindingFlags.Public | BindingFlags.Instance);
int count = (int)countProp.GetValue(listObj);

List<object> theList = new List<object>(count);
// 通过索引器逐个获取元素
PropertyInfo indexerProp = listType.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < count; i++)
{
    object item = indexerProp.GetValue(listObj, new object[] { i });
    theList.Add(item);
}

补充说明

你已经获取到的私有嵌套类型pType,可用于后续反射操作(比如访问该类型的私有属性、方法等)。

内容的提问来源于stack exchange,提问作者Cheyenne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:05:15