通过反射获取属性并设置其子属性

时间:2019-06-23 16:27:41

标签: c# class

之后,我必须通过字符串(通过featuresHome完成)在var property = typeof (featuresHome) .GetProperty ("homePosition");类中找到一个属性,然后我必须设置positionLake的{​​{1}}属性。

代码:

homePosition

目标是通过字符串找到“ featuresHome”类的属性,然后设置属性的值(“ PositionLake”)

谢谢!

1 个答案:

答案 0 :(得分:0)

featuresHome FeaturesHome = HomeList.Last().FeaturesHome;
var property = typeof(featuresHome).GetProperty("homePosition");

只需获取其HomePosition属性:

property.SetValue(FeaturesHome.HomePosition.PositionLake, "Mono Lake", null);
HomePosition hp = new HomePosition {PositionLake = "Mono Lake"} 

然后设置FeatureHome的HomePosition属性:

property.SetValue(FeaturesHome, hp, null);