Question

I am using reflection to set a property from within a reflected property. I have to use reflection as I don't know what the type the child propery will be, but each time I get System.Target.TargetException (on the prop.SetValue) prop is pointing to the correct property

I can find lot of examples of the SetValue, the problem that I am having, is I expect related to the fact that selectSubProcess is a PropertyInfo rather than a actual class

PropertyInfo selectedSubProcess = process.GetProperty(e.ChangedItem.Parent.Label);
Type subType = selectedSubProcess.PropertyType;
PropertyInfo prop = subType.GetProperty(e.ChangedItem.Label + "Specified");
if (prop != null)
        {
            prop.SetValue(process, true, null);
        }
Was it helpful?

Solution

It looks like process is "Type", not an instance of an object. in the line

prop.SetValue(process, true, null);

you need an instance of an object to set, not a Type.

Use "GetValue" to get an instance of the object you care about:

public void test()
{
  A originalProcess = new A();
  originalProcess.subProcess.someBoolean = false;

  Type originalProcessType = originalProcess.GetType();
  PropertyInfo selectedSubProcess = originalProcessType.GetProperty("subProcess");
  object subProcess = selectedSubProcess.GetValue(originalProcess, null);
  Type subType = selectedSubProcess.PropertyType;
  PropertyInfo prop = subType.GetProperty("someBoolean");
  if (prop != null)
  {
    prop.SetValue(subProcess, true, null);
  }

  MessageBox.Show(originalProcess.subProcess.someBoolean.ToString());
}


public class A
{
  private B pSubProcess = new B();
  public B subProcess
  {
    get
    {
      return pSubProcess;
    }
    set
    {
      pSubProcess = value;
    }
  }

}

public class B
{
  private bool pSomeBoolean = false;
  public bool someBoolean
  {
    get
    {
      return pSomeBoolean;
    }
    set
    {
      pSomeBoolean = true;
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top