22

リフレクションを使用して、クラスのネストされたプロパティに値を動的に設定しようとしています。誰でも私がこれを行うのを手伝ってくれますか?

私は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。これは、インスタンスを作成して毎回割り当てるのではなく、ネストされたプロパティに値を割り当てる方法を意味します。

前もって感謝します。!

4

3 に答える 3

60

プロパティを使用して国を取得してから、プロパティを使用して国のIDをPropertyInfo.GetValue設定するように呼び出す必要があります。CountryPropertyInfo.SetValueId

だからこのようなもの:

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);
}
于 2012-09-06T06:40:30.470 に答える