如何使用反射从FieldInfo获取System.Collections.Generic.List?
首先获取类型中的FieldInfo对象:
FieldInfo fieldInfo = typeof(SomeCl
as
s).GetField("listField", BindingFlags.Instance | BindingFlags.NonPublic);
然后获取该FieldInfo所属的类型:
Type fieldType = fieldInfo.FieldType;
判断该类型是否为List类型:
if(typeof(List<>).Is
As
signableFrom(fieldType.GetGenericTypeDefinition()))
如果是List类型,则使用反射创建List对象并将其赋值给FieldInfo:
object listObject = Activator.CreateInstance(fieldType);
fieldInfo.SetValue(someCl
as
sInstance, listObject);
完整代码示例:
using System;
using System.Collections.Generic;
using System.Reflection;
public cl
as
s SomeCl
as
s
private
List<int> listField = new List<int>();
public cl
as
s Program
public static void Main()
SomeCl
as
s someCl
as
sInstance = new SomeCl
as
s();
// 获取SomeClass类中名为listField的私有字段
FieldInfo fieldInfo = typeof(SomeClass).GetField("listField", BindingFlags.Instance | BindingFlags.NonPublic);
// 获取listField字段的类型
Type fieldType = fieldInfo.FieldType;
// 判断类型是否为List<int>
if(typeof(List<>).IsAssignableFrom(fieldType.GetGenericTypeDefinition()))
// 使用反射创建List<int>对象并将其赋值给listField字段
object listObject = Activator.CreateInstance(fieldType);
fieldInfo.SetValue(someClassInstance, listObject);
// 测试是否成功
List<int> listPropertyValue = (List<int>)fieldInfo.GetValue(someClassInstance);
listPropertyValue.Add(1);
Console.WriteLine(listPropertyValue[0]);