リフレクションを使用してオブジェクトのプロパティのプロパティを設定する

StackOverflow https://stackoverflow.com/questions/1402479

  •  05-07-2019
  •  | 
  •  

質問

2つのクラスがあります。

public class Class1 {
   public string value {get;set;}
}

public class Class2 {
   public Class1 myClass1Object {get;set;}
}

タイプClass2のオブジェクトがあります。 Class2でリフレクションを使用してvalueプロパティを設定する必要があります...つまり、リフレクションなしでそれを実行している場合、これは私がそれについてどうするかです:

Class2 myObject = new Class2();
myObject.myClass1Object.value = "some value";

リフレクションを使用してプロパティ「myClass1Object.value」にアクセスしながら、上記を実行する方法はありますか?

事前に感謝します。

役に立ちましたか?

解決

基本的に、2つのプロパティアクセスに分割します。最初に myClass1Object プロパティを取得してから、結果の value プロパティを設定します。

明らかに、プロパティ名を取得し、それを分割する形式を使用する必要があります。ドットで。たとえば、これはプロパティの任意の深さを行う必要があります:

public void SetProperty(object source, string property, object target)
{
    string[] bits = property.Split('.');
    for (int i=0; i < bits.Length - 1; i++)
    {
         PropertyInfo prop = source.GetType().GetProperty(bits[i]);
         source = prop.GetValue(source, null);
    }
    PropertyInfo propertyToSet = source.GetType()
                                       .GetProperty(bits[bits.Length-1]);
    propertyToSet.SetValue(source, target, null);
}

確かに、それよりも少し多くのエラーチェックが必要になるでしょう:)

他のヒント

プロパティ名が指定されているときにプロパティ値を取得する場合の回答を探していましたが、プロパティのネストレベルは不明です。

たとえば入力が「値」の場合&quot; myClass1Object.value&quot;のような完全修飾プロパティ名を提供する代わりに。

あなたの答えは、以下の私の再帰的な解決策に影響を与えました:

public static object GetPropertyValue(object source, string property)
{
    PropertyInfo prop = source.GetType().GetProperty(property);
    if(prop == null)
    {
      foreach(PropertyInfo propertyMember in source.GetType().GetProperties())
      { 
         object newSource = propertyMember.GetValue(source, null);
         return GetPropertyValue(newSource, property);
      }
    }
    else
    {
       return prop.GetValue(source,null);
    }
    return null;
}
   public static object GetNestedPropertyValue(object source, string property)
    {
        PropertyInfo prop = null;
        string[] props = property.Split('.');

        for (int i = 0; i < props.Length; i++)
        {
            prop = source.GetType().GetProperty(props[i]);
            source = prop.GetValue(source, null);
        }
        return source;
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top