访问另一个类中的类构造函数变量';作用
本文关键字:变量 作用 构造函数 另一个 访问 | 更新日期: 2023-09-27 17:58:43
我有一个接口后面的类。我们称之为DoStuff
,它看起来像这样:
public class DoStuff : IDoStuff
{
private int _stuffId; //class variable
public DoStuff(int stuffId)
{
_stuffId = stuffId;
}
...
}
在另一个类中,我们称之为Home
,按钮逻辑如下:
public partial class Home : Form
{
private readonly IStuffPresenter _presenter;
public Home(DoStuff doStuff)
{
InitializeComponent();
_presenter = new StuffPresenter(doStuff);
homeText.Text = doStuff.HomeText;
}
private void showLater_Click(object sender, EventArgs e)
{
int stuffId = //???
.....
showLater.Arguments.Add(string.Format("<StuffID>{0}</StuffID>", stuffId)); //how it's being used
}
我在DoStuff
类中使用stuffId
,我希望能够在这里使用它,而不必编写与再次获取ID相关的所有代码。如何从主页类(这是一个表单)中的按钮单击事件内的DoStuff
类访问stuffId
?
现在您已经提供了更多的代码,解决方案变得清晰起来。
问题的第一部分是设置_stuffId
的可访问性,以便可以在类范围之外使用它。为此,我建议将其作为公共财产:
public class DoStuff : IDoStuff
{
public int StuffId { get; set; } //class property
public DoStuff(int stuffId)
{
StuffId = stuffId;
}
//...
}
问题的下一部分是,您需要能够从单击事件中访问DoStuff
的实例。根据您现有的代码,我建议创建一个类级变量来存储它。然后,您可以从构造函数中设置它,然后在单击事件中使用它,如下所示:
public partial class Home : Form
{
private readonly IStuffPresenter _presenter;
private DoStuff _doStuff;//store it here so all functions can see it
public Home(DoStuff doStuff)
{
InitializeComponent();
_doStuff = doStuff;//set the class variable here so we can use it later
_presenter = new StuffPresenter(doStuff);
homeText.Text = doStuff.HomeText;
}
private void showLater_Click(object sender, EventArgs e)
{
int stuffId = _doStuff.StuffId;//we can access the instance here now
//.....
showLater.Arguments.Add(string.Format("<StuffID>{0}</StuffID>", stuffId)); //how it's being used
}
当然,通过StuffPresenter
访问该值是可能的,但在不知道其实现的情况下,我不能肯定
尝试更改类以公开_stuffId
。
由于CCD_ 11是CCD_。如果希望构造函数管理变量的设置方式,可以将变量包装在属性中以公开它,也可以仅将属性与私有setter一起使用。
public class DoStuff : IDoStuff
{
public int StuffId { get; private set; }
public DoStuff(int stuffId)
{
StuffId = stuffId;
}
}
这将允许您访问但不更改它:
int stuffId = stuff.StuffId;
或者,您可以更改_stuffId
的可访问性:
public class DoStuff : IDoStuff
{
public int _stuffId;
public DoStuff(int stuffId)
{
_stuffId = stuffId;
}
}
但这样做将允许更改