如何使用C#Reflection将Vaues设置为嵌套属性。?

我试图使用reflection动态地将值设置为类的嵌套属性。 任何人都可以帮我这样做。

我有一个类Region如下所示。

 public class Region { public int id; public string name; public Country CountryInfo; } public class Country { public int id; public string name; } 

我有一个Oracle Data reader来提供Ref游标的值。

这会给我一个

ID,姓名,COUNTRY_ID,COUNTRY_NAME

我可以通过下面的方式将值分配给Region.Id,Region.Name。

 FieldName="id" prop = objItem.GetType().GetProperty(FieldName, BindingFlags.Public | BindingFlags.Instance); prop.SetValue(objItem, Utility.ToLong(reader_new[ResultName]), null); 

对于嵌套属性,我可以通过读取Fieldname创建实例来为下面的值赋值。

 FieldName="CountryInfo.id" if (FieldName.Contains('.')) { Object NestedObject = objItem.GetType().GetProperty(Utility.Trim(FieldName.Split('.')[0]), BindingFlags.Public | BindingFlags.Instance); //getting the Type of NestedObject Type NestedObjectType = NestedObject.GetType(); //Creating Instance Object Nested = Activator.CreateInstance(typeNew); //Getting the nested Property PropertyInfo nestedpropinfo = objItem.GetType().GetProperty(Utility.Trim(FieldName.Split('.')[0]), BindingFlags.Public | BindingFlags.Instance); PropertyInfo[] nestedpropertyInfoArray = nestedpropinfo.PropertyType.GetProperties(); prop = nestedpropertyInfoArray.Where(p => p.Name == Utility.Trim(FieldName.Split('.')[1])).SingleOrDefault(); prop.SetValue(Nested, Utility.ToLong(reader_new[ResultName]), null); Nestedprop = objItem.GetType().GetProperty(Utility.Trim(FieldName.Split('.')[0]), BindingFlags.Public | BindingFlags.Instance); Nestedprop.SetValue(objItem, Nested, null); } 

以上为Country.Id赋值。

但是因为我每次创建实例时都无法获得之前的Country.Id值,如果我选择Next Country.Name。

任何人都可以告诉可以为objItem(that is Region).Country.Id指定值objItem.Country.NameobjItem.Country.Name 。 这意味着如何将值分配给嵌套属性,而不是每次创建实例和分配。

提前致谢。!

您应该使用Country属性调用PropertyInfo.GetValue来获取国家/地区,然后使用Id属性调用PropertyInfo.GetValue来设置Country的ID。

所以这样的事情:

 public void SetProperty(string compoundProperty, object target, object value) { string[] bits = compoundProperty.Split('.'); for (int i = 0; i < bits.Length - 1; i++) { PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]); target = propertyToGet.GetValue(target, null); } PropertyInfo propertyToSet = target.GetType().GetProperty(bits.Last()); propertyToSet.SetValue(target, value, null); } 

获取Nest属性,例如Developer.Project.Name

 private static System.Reflection.PropertyInfo GetProperty(object t, string PropertName) { if (t.GetType().GetProperties().Count(p => p.Name == PropertName.Split('.')[0]) == 0) throw new ArgumentNullException(string.Format("Property {0}, is not exists in object {1}", PropertName, t.ToString())); if (PropertName.Split('.').Length == 1) return t.GetType().GetProperty(PropertName); else return GetProperty(t.GetType().GetProperty(PropertName.Split('.')[0]).GetValue(t, null), PropertName.Split('.')[1]); }