在反映的专有信息中的设置值
本文关键字:设置 信息 | 更新日期: 2023-09-27 18:33:51
我正在使用反射从反射属性中设置属性。我必须使用反射,因为我不知道子属性的类型是什么,但是每次我得到System.Target.TargetException(在道具上。SetValue) 属性指向正确的属性
我可以找到很多 SetValue 的例子,我遇到的问题是,我希望与 selectSubProcess 是一个 PropertyInfo 而不是一个实际的类这一事实有关。
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);
}
看起来进程是"类型",而不是对象的实例。 在行中
prop.SetValue(process, true, null);
您需要设置对象的实例,而不是类型。
使用"GetValue"获取您关心的对象的实例:
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;
}
}
}