简体   繁体   中英

How to access an object's property at array[i] (C#)

I created an array of type Account . Then I populated the array with Account objects.
Now I am trying to access the object at array[i] so that I can modify one of its variables and move on the next object.

public class Account {
    string client;
    string firstName;
    string lastName;
    string planName;
    string startDate;
    string endDate;
    string eeCost;
    string erCost;
    string total;
}

Account[] webData = new Account[3];

for(int i = 0; i < webData.Length; i++) {
    webData[i] = new Account();
}

How can I access the object at webData[i] ?

for(int i = 0; i < webData.Length; i++) {
    webData[i].firstName = "Anna";
}

将firstName设为添加有getter / setter的公共变量,然后就可以访问属性。默认情况下,如果不存在访问修饰符,则CLR会将其视为Private

public string FirstName { get; set; }

Everything is fine in your example. That's exactly how you access a field.

The problem is that these fields are not public - in C#, default access modifier for class members is private .

It should be declared as public in order to make it accessible outside the class:

public class Account {
    public string client;
    public string firstName;
    public string lastName;
    public string planName;
    public string startDate;
    public string endDate;
    public string eeCost;
    public string erCost;
    public string total;
}

By the way, it is better to use properties. Read more about:
- What is auto-property? at MSDN
- And why you should use it at Programmers.SE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM