日期:2014-05-18  浏览次数:20892 次

动态反射方法的问题
有个问题请教下,
用反射方法调用时,为什么没法初始化当前窗体的控件内容
public class TTWinForm
{
  public static void InvokeChildMethod(string ChildTypeString, string methodName)
  {
  Type type = Type.GetType(ChildTypeString);
  object form = Activator.CreateInstance(type);
  MethodInfo methodInfo = type.GetMethod(methodName);
  methodInfo.Invoke(form, null);
  }
}

TTWinForm.InvokeChildMethod(typeof(TrainDo).ToString(), "LoadForm"); 
被调用的子窗体
 public partial class TrainDo : Form
  {
public void LoadForm()
  {
  button1.Text = "1212";
}
}

------解决方案--------------------
TTWinForm 修改下
C# code
public class TTWinForm
{
    /// <summary>
    /// MDI打开子窗口(只是一个实例)
    /// </summary>
    /// <param name="MDIForm">父窗口</param>
    /// <param name="childType">子窗口类型</param>
    /// <returns></returns>
    public static Form OpenChildWindow(Form MDIForm, Type childType)
    {
        Form f = ContainMDIChild(MDIForm, childType);
        if (f == null)
        {
            f = (Form)Activator.CreateInstance(childType);
            f.MdiParent = MDIForm;
        }

        f.Show();
        f.Focus();

        return f;
    }

    /// <summary>
    /// 查找是否包含子窗口
    /// </summary>
    /// <param name="MDIForm">父窗口</param>
    /// <param name="childType">子窗口类型</param>
    /// <returns></returns>
    private static Form ContainMDIChild(Form MDIForm, Type childType)
    {
        foreach (Form f in MDIForm.MdiChildren)
        {
            if (f.GetType() == childType)
            {
                f.TopMost = true;
                return f;
            }
        }

        return null;
    }

    public static void InvokeChildMethod(Form f, Type childType, string methodName)
    {
        MethodInfo methodInfo = childType.GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
        methodInfo.Invoke(f, null);
    }
}