Sra*_*van 20 c# reflection propertyinfo
我试图使用反射动态地将值设置为类的嵌套属性.任何人都可以帮我这样做.
我正在上课Region.
public class Region
{
public int id;
public string name;
public Country CountryInfo;
}
public class Country
{
public int id;
public string name;
}
Run Code Online (Sandbox Code Playgroud)
我有一个Oracle数据阅读器来提供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);
Run Code Online (Sandbox Code Playgroud)
对于嵌套属性,我可以通过读取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);
}
Run Code Online (Sandbox Code Playgroud)
以上赋值给Country.Id.
但是,因为我每次都创建实例,所以Country.Id如果我去Next Country.Name,我就无法获得之前的值.
有谁可以告诉分配值的objItem(that is Region).Country.Id和objItem.Country.Name.这意味着如何将值分配给嵌套属性,而不是每次创建实例和分配.
提前致谢.!
Jon*_*eet 51
您应该PropertyInfo.GetValue使用该Country属性来调用该国家/地区,然后PropertyInfo.SetValue使用该Id属性在该国家/地区设置 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12401 次 |
| 最近记录: |