如何在WinForm启动时通过MessageBox显示类中的信息
问题修复方案
你的代码无法运行主要有两个核心问题:一是Info方法里的字符串是局部变量,外部无法获取;二是MessageBox.Show不能直接接收自定义类对象作为参数,需要传入字符串类型的值。以下是两种可行的修改方式:
方案一:用类属性存储信息
修改Greeting类,将保密信息定义为类的公开只读属性:
public class Greeting { // 定义只读属性存储保密信息 public string ConfidentialInfo { get; } = "Please remember that all information is confidential!"; }
然后修改窗体Load事件代码,读取属性值并传入MessageBox:
private void frmCustomerInfo_Load(object sender, EventArgs e) { Greeting hello = new Greeting(); MessageBox.Show(hello.ConfidentialInfo); }
方案二:让方法返回字符串
调整Info方法的返回类型为string,直接返回保密信息:
public class Greeting { public string Info() { return "Please remember that all information is confidential!"; } }
修改窗体Load事件,调用方法获取字符串后显示:
private void frmCustomerInfo_Load(object sender, EventArgs e) { Greeting hello = new Greeting(); MessageBox.Show(hello.Info()); }
内容的提问来源于stack exchange,提问作者Josh Lasley
相关产品推荐
相关产品推荐

