尝试使用反射将嵌套属性的值设置为两级,但是获取对象并不会导致目标对象错误。键入的obj看起来像这样: project.EnvironmentalAessment.SomeDocument.Review
var _review = new Review() { .... };
var docProp = project.EnvironmentalAssessment.GetType().GetProperty(techStudy.DocumentProperty);
var docType = docProp.PropertyType;
var reviewProp = docType.GetProperty("Review");
var reviewType = reviewProp.GetType();
project.EnvironmentalAssessment
.GetType()
.GetProperty(techStudy.DocumentProperty)
.PropertyType
.GetProperty("Review")
.SetValue(reviewProp, _review, null);
非常感谢任何见解。谢谢!
答案 0 :(得分:1)
project.EnvironmentalAssessment
.GetType()
.GetProperty("SomeDocument")
.PropertyType
.GetProperty("Review")
.SetValue(project.EnvironmentalAssessment.SomeDocument, _review, null);
或者,如果您不知道文档属性的名称:
var docProp = project.EnvironmentalAssessment
.GetType()
.GetProperty(techStudy.DocumentProperty);
docProp.PropertyType.GetProperty("Review")
.SetValue(docProp.GetValue(project.EnvironmentalAssessment), _review, null);
答案 1 :(得分:1)
您还可以使用动态类型来解决此问题,这将使其更容易。我不知道它在性能方面是否比使用反射更有效。
dynamic project = ...;
var review = new Review() { .... };
project.EnvironmentalAessment.SomeDocument.Review = review;