开发者

Creating an array from a constructor in C#

So I've been trying to figure out how to populate an array with an object I have created in C#. I found this cod开发者_JAVA技巧e sample which explains a bit about what I need to do.

for (int i = 0;i<empArray.Length;i++)
       {
           empArray[i] = new Employee(i+5);
       }

But what happens if I pass more than one parameter into my constructor? Will this look any different? Like empArray[i] = new Employee(i, j, k); and so on. And if so how will read these objects out of the array, to say the Console. Would

Console.WriteLine(empArray[i])

do the trick if the object has more than one variable passed into it, or will I need a multi dimensional array? I apologize for all the questions, just a little new to C#.


The parameters passed in to the constructor are simply information for the object to initialize itself. No matter how many parameters you pass in, only a single Employee object will come out, and that object will be put in empArray[i].

You will always access the Employee objects using empArray[<index>] where index is an integer where 0 <= index < empArray.Length.

Console.WriteLine takes a string or any object with a ToString() method on it. So if the Employee object implements ToString(), then Console.WriteLine(empArray[i]) will work. You might implement ToString() like this:

public string ToString()
{
    return String.Format("{0} {1}", this.FirstName, this.LastName);
}


Yes, this would work. In the statement array[i] the i is used as a reference to a position in a array, and has nothing to do with the actual contents of the object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜