Inject a value to object properties at run time in c#
I have a class like this:
public class ChildForm extends System.Windows.Forms.Form{
public int childId;
}
I call it 开发者_C百科like this:
Type baseType = Type.GetType("ChildForm");
System.Windows.Forms.Form formCall = (Form)System.Activator.CreateInstance(baseType);
//How can i set childId properties here?
The ChildForm could be many forms, that's why i need to use reflection and use the parent form to display it.But i don't know how to set the child properties. can this be done with properties injection?
Thanks in advance.What you have there is a field, not a property. And to set its value you could do this:
var baseType = Type.GetType("ChildForm");
System.Windows.Forms.Form formCall = (ChildForm)System.Activator.CreateInstance(baseType);
baseType.GetField("childId").SetValue(formCall, 5);
精彩评论