前面的贴是自己搞错了,原来我传入别的对象也是不能访问私有成员的,开始可以的原来是公共的属性
那我怎么才可以直接访问私有对象呢?网上给出的例子都是访问一些私有的简单的属性或者变量(例如String类型的)
但我的私有成员是一些复杂的对象来的,例如控件,表格等,我怎么直接获得他的引用而不是通过
GetValue,SetValue等方法访问,因为这样根本无法访问复杂的表格对象的
还有就是Friend定义的控件根本无法通过GetField方法获取
能否通过反射然后把它转换成对象变量直接引用操作呢?
下面代码无法获取TextBox1的引用
dim mytype as Type = MyForm.GetType()
dim fieldinfo as System.Reflection.FieldInfo = mytype.GetField("TextBox1", System.Reflection.BindingFlags.NonPublic or System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Public)
dim objField as object= fieldinfo.GetValue(MyForm) '''这里出错,因为fieldinfo返回Nothing
if not objField is nothing then
MessageBox.Show(objField.text)
end if
------解决方案--------------------
通过
Dim memberInfo As System.Reflection.MemberInfo = mytype.GetMember("TextBox1", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.Public)(0)
可以看到MemberType 是Property
所以应该是
Dim fieldinfo As System.Reflection.PropertyInfo = mytype.GetProperty("TextBox1", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.Public)
------解决方案--------------------
贴一段7年前写的代码你参考下吧。。。
Form form;
try
{
form = Activator.CreateInstance(t) as Form; //参数t 就是你代码中的mytype as Type = MyForm.GetType()
}
catch(Exception ex)
{
MessageBoxShow((IWin32Window)this, ex.Message, "", MessageBoxButtons.OK, 1);
return;
}
foreach (Control ctrl in form.Controls)
{
string fieldTypeName = ctrl.GetType().ToString();
//如果是Button,取其值,此处需要和BaseForm中的按钮权限控制部分一致
switch (fieldTypeName)
{
//如果是容器类,则递归查找子控件。
case "System.Windows.Forms.ToolStrip":
ToolStrip ts = ctrl as ToolStrip;
GetButton(ts.Items);
break;
case "System.Windows.Forms.Panel":