【发布时间】:2020-05-14 00:22:51
【问题描述】:
课堂作业要求我们创建一个简单的能源账单。第一次生成一个 ID 号,我想将其复制到第二个表格,但是我不断收到以下信息:
错误 CS0122 'Form1.idgen' 由于其保护级别而无法访问
因为我要参考第一形式的很多价值观,所以我只想了解问题是什么以及如何克服它以备将来使用
这是Form1的代码:
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 Bill_Generator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
Random r = new Random();
var x = r.Next(0, 1000000);
string v = x.ToString("000");
idgen.Text = v;
}
public void Timer1_Tick(object sender, EventArgs e)
{
date.Text = DateTime.Now.ToString("dddd , MMM dd yyyy hh:mm:ss");
}
public void Gen_button_Click(object sender, EventArgs e)
{
Form2 openform = new Form2();
openform.Show();
}
public void Calc_Click(object sender, EventArgs e)
{
double preamt = Convert.ToDouble(prebox.Text);
double curramt = Convert.ToDouble(currbox.Text);
double billamt = curramt - preamt;
billbox.Text = Convert.ToString(billamt);
}
}
}
这是到目前为止 Form2 的代码:
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 Bill_Generator
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
System.Windows.Forms.Form f = System.Windows.Forms.Application.OpenForms["Form1"];
iddisp.Text = ((Form1)f).idgen.Text();
}
private void Form2_Load(object sender, EventArgs e)
{
date.Text = DateTime.Now.ToString("dddd , MMM dd yyyy hh:mm:ss");
}
}
}
【问题讨论】:
-
您可以更改可访问性。但是,请参阅这些问答:stackoverflow.com/questions/8566/…、stackoverflow.com/questions/1665533/…。更改可访问性确实是最后的手段,而且永远不需要。
标签: c# winforms visual-studio-2019