我想使用反射動態地設置一個值爲嵌套屬性的類。任何人都可以幫助我做到這一點。如何使用C#反射將Vaues設置爲嵌套屬性。
我有一個類Region
像下面。
public class Region
{
public int id;
public string name;
public Country CountryInfo;
}
public class Country
{
public int id;
public string name;
}
我有一個Oracle數據讀取器來提供參考光標的值。
,這將給我作爲
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="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.Name
分配數值。這意味着如何將值分配給嵌套屬性,而不是每次創建實例和分配。
在此先感謝。
http://stackoverflow.com/questions/1954746/using-reflection的可能的複製-in -c-sharp-to-get-properties-of-an-nested-object –