我正在嘗試使用反射設置對象的屬性。 該屬性是一個ICollection - 如果集合尚未實例化,我想完成此操作。我的問題是,我有問題獲得內部類型將ICollection的通過c#中的反射訪問內部類型的ICollection <SomeInnerClass>#
這是我的課
public class Report(){
public virtual ICollection<Officer> OfficerCollection { get; set; }
}
我試圖通過反射來訪問下面定義的「官」類
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?
}
爲什麼你需要使用反射?你的財產已經公開。 – Gabe
這是一個非常簡單的例子;-) –
如果你打算設計一個例子,你應該明確它。在這種情況下,將'Officer'同時作爲類的名稱和該類的實例集合的屬性的名稱是不必要的混淆。 – Gabe