【发布时间】:2017-10-06 17:55:05
【问题描述】:
这应该很简单,但我很难看到任何结果。
我的表单代码如下:
//Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NotepadRW
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected TextBox textReadInfo;
public void SetReadInfo(String str)
{
txtReadInfo.Text = str;
}
}
}
我还有以下程序代码:
//Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NotepadRW
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
Application.Run(form1);
form1.SetReadInfo("Hi");
}
}
}
结果如下:
为什么不显示我提供的字符串?我是否没有正确理解该程序如何与 Windows 窗体一起工作?调用 Form1 的新实例时,Program.cs 的 Main() 方法的执行是否停止?
注意:我已经尝试过使用文本框和富文本框。结果相同。
加分: 我是否正确遵循封装?我打算将文本框修改为可公开访问(这将起作用),但我认为这是“正确”的做法。
【问题讨论】:
-
txtReadInfo.Text = str是拼写错误还是 txtReadInfo 定义在我们看不到的地方? -
在
InitializeComponent通话后为什么不做this.SetReadInfo("Hi")? -
您将在 Application.Run 之后分配该文本。这将启动 GUI 事件循环并且在主窗体关闭之前不会退出。在表单构造函数和应用程序运行之间移动这条线。