如何读取存储在类库中的对象的属性

时间:2018-01-12 14:31:03

标签: c#

我对编程非常陌生并且不断遇到这个问题:

我使用visual studio 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");
    }
}

ui代码

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}";
    }
}

/ *好的,这就是问题所在。我们不会认可home.AreaDescription在第30行吗?  *错误消息是 - >当前上下文中不存在“home”这个名称

1 个答案:

答案 0 :(得分:1)

由于您是编程新手,为了搜索问题的简单解决方案,您应该查看c#中的acces修饰符。

https://docs.microsoft.com/fr-fr/dotnet/csharp/language-reference/keywords/access-modifiers

解释你的情况,你的变量

    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");

仅在您的CreateArea方法中可见。

为了从其他类或引用您的库的其他应用程序到达变量或属性,您应该声明像

这样的公共属性
public int AreaID { get; set; }
public string AreaTitle { get; set; }
public string AreaDescription { get; set; }

变量。

为了从引用库的应用程序到达库类的变量或属性,应使用public acces修饰符。 根据您的目标,您应该使用内部,受保护或私有访问修饰符。

如果您查看响应顶部的链接,您可以找到详细的信息。