0

Trying to build a Windows 8 App using C# and XAML.

I've created a class:

class Tile
{
    public Tile(int ID, string Name, double Frequency, double Divider, int Value, int Turns, int StartLevel)
    {
        this.ID = ID;
        this.Name = Name;
        this.Frequency = Frequency;
        this.Divider = Divider;
        this.Value = Value;
        this.Turns = Turns;
        this.StartLevel = StartLevel;
    }

    private int ID { get; set; }
    private string Name { get; set; }
    private double Frequency { get; set; }
    private double Divider { get; set; }
    private int Value { get; set; }
    private int Turns { get; set; }
    private int StartLevel { get; set; }
}

I've added objects to a list:

List<Tile> tList = new List<Tile>();

tList.Add(new Tile(0, "Example1", 0.08, 1.00, 0, 7, 1));
tList.Add(new Tile(1, "Example2", 0.21, 1.25, 0, 0, 1));

When using standard C#, I'm able to access the properties of an object like such:

foreach (Tile t in tList)
{
    int test = t.ID;
}

The Problem: In my foreach statement above, when I type "t." all that comes up in this list of available elements is:

Equals GetHashCode GetType ToString

I Expect: The following elements to appear:

ID Name Frequency Divider Value Turns StartLevel

What am I missing here?


Your properties in your Tile class are set to private. To be able to access the properties from outside the class you will need to declare them as public:

public class Tile
{
    public int ID { get; set; }
    public string Name { get; set; }
    public double Frequency { get; set; }
    public double Divider { get; set; }
    public int Value { get; set; }
    public int Turns { get; set; }
    public int StartLevel { get; set; }
}

You can keep your same constructor, although that will end up being a mess to maintain as you add/subtract properties. Another way you can instantiate your list of Tile objects is like so:

List<Tile> tList = new List<Tile>
{
    new Tile
    {
       ID = 0,
       Name = "Example1"
    }
};

...for as many public properties as you need to set.

4

1 回答 1

4

您在 Tile 类中的属性设置为私有。为了能够从类外部访问属性,您需要将它们声明为公共:

public class Tile
{
    public int ID { get; set; }
    public string Name { get; set; }
    public double Frequency { get; set; }
    public double Divider { get; set; }
    public int Value { get; set; }
    public int Turns { get; set; }
    public int StartLevel { get; set; }
}

您可以保留相同的构造函数,尽管在添加/减去属性时维护起来会变得一团糟。另一种实例化 Tile 对象列表的方法如下:

List<Tile> tList = new List<Tile>
{
    new Tile
    {
       ID = 0,
       Name = "Example1"
    }
};

...为您需要设置的尽可能多的公共属性。

于 2013-06-15T21:31:30.570 回答