我是 c# 的新手,我想我想这样做,但也许我不知道也不知道!
我有一个名为 SyncJob 的课程。我希望能够创建一个实例来备份“我的文档”中的文件(只是一个示例)。然后我想创建另一个 SyncJob 实例来备份另一个文件夹中的文件。所以,换句话说,我可以在内存中拥有同一个类的多个实例。
我首先在我的代码中声明对象 var,以便它下面的所有方法都可以访问它。
我的问题是:虽然使用相同的实例名称会在内存中为对象创建一个新实例,但我该如何管理这些对象?意思是,如果我想设置其中一个属性,我该如何告诉编译器将更改应用到哪个实例?
正如我一开始所说,也许这是管理同一类的多个实例的错误方案......也许有更好的方法。
这是我的原型代码:
Form1.cs
namespace Class_Demo
{
public partial class Form1 : Form
{
BMI patient; // public declarition
public Form1()
{
InitializeComponent();
}
private void btnCreateInstance1_Click(object sender, EventArgs e)
{
patient = new BMI("Instance 1 Created", 11); // call overloaded with 2 arguments
displayInstanceName(patient);
}
private void displayInstanceName(BMI patient)
{
MessageBox.Show("Instance:"+patient.getName()+"\nwith Age:"+patient.getAge());
}
private void btnCreateInstance2_Click(object sender, EventArgs e)
{
patient = new BMI("Instance 2 Created", 22); // call overloaded with 2 arguments
displayInstanceName(patient);
}
private void btnSetNameToJohn_Click(object sender, EventArgs e)
{
// this is the issue: which instance is being set and how can I control that?
// which instance of patient is being set?
patient.setName("John");
}
private void btnDisplayNameJohn_Click(object sender, EventArgs e)
{
// this is another issue: which instance is being displayed and how can I control that?
// which instance of patient is being displayed?
displayInstanceName(patient);
}
}
}
类文件:
namespace Class_Demo
{
class BMI
{
// Member variables
public string _newName { get; set; }
public int _newAge { get; set; }
// Default Constructor
public BMI() // default constructor name must be same as class name -- no void
{
_newName = "";
_newAge = 0;
}
// Overload constructor
public BMI(string name, int age)
{
_newName = name;
_newAge = age;
}
//Accessor methods/functions
public string getName()
{
return _newName;
}
public int getAge()
{
return _newAge;
}
public void setName(string name)
{
_newName = name;
}
}
}