c# - 通过 C# 中的反射访问 ICollection<SomeInnerClass> 的内部类型

标签 c# .net reflection

我正在尝试使用反射为对象设置属性。 该属性是一个 ICollection - 如果 Collection 尚未实例化,我想完成它。我的问题是我在获取 ICollection 的内部类型时遇到问题

这是我的类(class)

public class Report(){
    public virtual ICollection<Officer> OfficerCollection { get; set; }
}

我正在尝试通过反射访问下面定义的“Officer”类

public class Officer(){
    public string Name{ get; set; }
}

代码片段

Report report = new Report()

PropertyInfo propertyInfo = report.GetType().GetProperty("OfficerCollection");
object entity = propertyInfo.GetValue(report, null);
if (entity == null)
{
    //How do I go about creating a new List<Officer> here?
}

最佳答案

试一试:

Report report = new Report();

PropertyInfo propertyInfo = report.GetType().GetProperty("Officer");
object entity = propertyInfo.GetValue(report, null);
if (entity == null)
{
    Type type = propertyInfo.PropertyType.GetGenericArguments()[0];
    Type listType = typeof(List<>).MakeGenericType(type);

    var instance = Activator.CreateInstance(listType);

    propertyInfo.SetValue(...);
}

关于c# - 通过 C# 中的反射访问 ICollection<SomeInnerClass> 的内部类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7933635/

相关文章:

c# - 检测数据库查询更新

c# - “Could not find type” 在设计器中加载窗体时出错

c# - 如何获取执行上下文菜单的控件名称

c# - 如何防止在 .NET 中智能加载 DLL?

reflection - 如何用threejs实现逼真反射

scala - 如何识别没有底层java字段的scala构造函数参数 'fields'?

c# - 具有多项选择的内联 if-else 语句

c# - 使用动态加载的 .Net 程序集进行二进制序列化

c# - 我可以用二进制而不是十六进制嵌入数字吗?

java - 使用反射获取Java数组中的字段 "length"