试图使用反射设置嵌套属性的值两层,但我得到一个对象并不不是目标对象错误。类型化的对象看起来像这样: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);
任何见解将不胜感激。谢谢!
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);
您也可以使用动态类型来解决这个问题,这将使它更容易。我不知道在性能方面是否会比使用反射更有效。
dynamic project = ...;
var review = new Review() { .... };
project.EnvironmentalAessment.SomeDocument.Review = review;