开发者

Inject a value to object properties at run time in c#

开发者 https://www.devze.com 2023-02-07 18:50 出处:网络
I have a class like this: public class ChildForm extends System.Windows.Forms.Form{ public int childId;

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消