【发布时间】:2018-01-12 14:31:03
【问题描述】:
我是编程新手,经常遇到这个问题:
我使用 Visual Studios 2015 创建了一个 Windows 应用程序,并向其中添加了一个类库来存储这些类。该库在引用中链接到应用程序,并且屏幕顶部的 using:namespace 命令已写入,但我似乎无法使用类中对象的存储数据。
班级
public class Area
{
//field -> properties of the object
public int AreaID { get; set; }
public string AreaTitle { get; set; }
public string AreaDescription { get; set; }
// constructor -> creates objects
public Area (int id, string title, string description)
{
this.AreaID = id;
this.AreaTitle = title;
this.AreaDescription = description;
}
//method that uses constructor to create ('instantiate') objects
public static void CreateArea()
{
Area home = new Area(1, "Home", "This is your home");
Area area2 = new Area(2, "Field", "Youre at a field");
Area area3 = new Area(3, "Mine", "Youre in a mine");
Area area4 = new Area(4, "Market", "Youre at a market");
}
}
用户界面代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Area.CreateArea(); //to make shure the 4 objects exist
}
// just to test if button works, and when program stops working
public int counter = 1;
public void btnImput_Click(object sender, EventArgs e)
{
lblTitle.Text = $"counter is {counter}";
counter++;
}
public void btnCreate_Click(object sender, EventArgs e)
{
ReportAreaDiscription(home); //doesnt recognise home
lblTitle.Text = home.AreaDescripting; //doesnt work either
}
//im trying a method cosue just typing the text didnt work either
public void ReportAreaDiscription(Area areadiscription)
{
lblDescription.Text = $"{areadiscription.AreaDescription}";
}
}
/* 好的,这就是问题所在。为什么程序不能识别第 30 行的 home.AreaDescription? * 错误信息是 -> 当前上下文中不存在名称“home”
【问题讨论】:
-
因为“home”是一个既没有声明也没有实例化的变量。我希望您想在表单中创建一个类型为 Area 的变量。您只是在 Area 上调用静态方法。就是这样。
-
home 被用作
CreateArea范围内的局部变量,并且在它之外没有范围。您需要在btnCreate_Click的范围内声明home才能使其正常工作。你还有home.AreaDescripting拼写错误 -
CreateArea不应该是Area类的成员。如果您需要Area的实例,那么引用它们的变量应该在正确的范围内。在何处、何时以及由谁实例化它们取决于... -
新用户,请客气,至少问题已经形成了
标签: c#