リフレクションを使用して、クラスのネストされたプロパティに値を動的に設定しようとしています。誰でも私がこれを行うのを手伝ってくれますか?
私はRegion
以下のようなクラスを持っています。
public class Region
{
public int id;
public string name;
public Country CountryInfo;
}
public class Country
{
public int id;
public string name;
}
参照カーソルから値を提供する Oracle データ リーダーがあります。
それは私に
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
。
しかし、私は毎回インスタンスを作成しているのでCountry.Id
、Next Country.Name に行くと以前の値を取得できませんでした。
objItem(that is Region).Country.Id
とに値を代入する方法を教えてくださいobjItem.Country.Name
。これは、インスタンスを作成して毎回割り当てるのではなく、ネストされたプロパティに値を割り当てる方法を意味します。
前もって感謝します。!