creating an array of objects?
It seems like this question gets asked frequently, but having looked through all of them, I find I'm still without aid. I'm taking my first step into oop, and I need to create an object with an attribute "Products" that is an array of up to 7 possible开发者_StackOverflow中文版 objects of class "Product". I just just barely understand the {get;set;} method, and am reading up on it, but I was hoping I could get some help with the syntax of what I'm trying to do here. I'm using C#. My code is below:
public class Submission
{
public Submission() {}
public int SubmissionId {get;set;}
public int CustId {get;set;}
public int BroId {get;set;}
public int Coverage {get;set;}
public Array Products // what goes here? It's a mystery.
}
In this case, I think you don't want an auto-implemented property. Instead, do it like this:
//backing store for your public property
private Product[] _products = new Product[7];
public Product[] Products { get {return _products;}}
and then in the constructor:
foreach(var item in _products) {item = new Product(); }
You could do this with a private setter rather than an explicit backing store, but I think this way is easier as far as setting up the size of the array goes.
Notice that I only provided a getter for the property. You don't want a setter, as that would allow someone to replace your property with a whole new array. Just providing a getter will still allow someone to manipulate the property. Also, normally I would recommend a collection rather than an array for this, but since you want a fixed-size for the number of items an array might be a better fit.
If you are up to using generic collections, I would use:
public List<Product> Products { get; private set; }
or some variation thereof.
You can write it like this:
public Products[] { get; set; }
and in the constructor of your class:
public Submission() {
Products = new Product[7];
}
Use an IList
. You can use the auto property with it.
精彩评论