我正在尝试使用反射为对象设置属性。 该属性是一个 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/