【发布时间】:2012-08-30 22:17:22
【问题描述】:
我正在尝试使用反射动态地为类的嵌套属性设置一个值。谁能帮我做这件事。
我正在上课Region,如下所示。
public class Region
{
public int id;
public string name;
public Country CountryInfo;
}
public class Country
{
public int id;
public string name;
}
我有一个 Oracle 数据阅读器来提供来自 Ref 游标的值。
这会给我
Id,name,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="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赋值。
但是由于我每次都在创建实例,因此如果我选择 Next Country.Name,我无法获得以前的 Country.Id 值。
谁能告诉可以为objItem(that is Region).Country.Id 和objItem.Country.Name 赋值。这意味着如何为嵌套属性分配值,而不是每次都创建实例并分配。
提前致谢!
【问题讨论】:
-
这不是@AdiLester 建议的stackoverflow.com/questions/1954746/… 的副本。此 OP 专门询问设置值。另一个询问获取价值。而且由于这个其他链接帮助了我并且它是相关的,所以我也会在这里发布。这篇 SO 帖子向您展示了如何设置一个值,从一种类型转换为另一种类型(例如,string => int)。 stackoverflow.com/questions/1089123/…
标签: c# reflection propertyinfo