简体   繁体   中英

In C# how do I get the properties of an object that is inside an array?

I am having trouble trying to reference the properties of an object that I have inserted into an array using the following method.

    public static void AddEmployees()
    {
        string empID;
        decimal empWage;
        int count = 0;
        do
        {
            Console.Write("Please enter the employee ID number: ");
            empID = Convert.ToString(Console.ReadLine());

            Console.Write("Please enter the employee wage: ");
            empWage = Convert.ToDecimal(Console.ReadLine());

            var employeeObj = CreateEmployee(empID, empWage);
            employeeArray[count] = employeeObj;
            ++count;

        } while (count < 6);

    }

I would like to print out the information in this array in some sort of readable format, but I don't know how to reference empWage or empID. Ideally I'd like to use some sort of foreach loop like follows:

    public static void DisplayEmployees()
    {
        foreach (var obj in employeeArray)
        {
            Console.WriteLine("Employee ID: {0}", empID);
            Console.WriteLine("Employee Wage: {0}", empWage);
            Console.WriteLine();
        }
    }

You almost had it:

foreach (var obj in employeeArray)
{
    Console.WriteLine("Employee ID: {0}", obj.empID);
    Console.WriteLine("Employee Wage: {0}", obj.empWage);
    Console.WriteLine();
}

Update:

If employeeArray is of type object[] , you cannot refer directly to properties defined in class Employee .

How to fix it:

Instead of object[] use a List<Employee> , for example:

public static List<Employee> employees  = new List<Employee>();

You will also need to change the way you add items to the list:

var employeeObj = CreateEmployee(empID, empWage);
employees.Add(employeeObj);

Finally, the return type of CreateEmployee should be Employee (not object ).

The quickest answer to your question is that you can cast the object in the array.

((Employee)obj).empID

You haven't shown how you defined the array; if it is an array of Employee then you can safely have the cast occur in the foreach but since you are getting errors I am guessing that your array might be of object or something higher in the inheritance hierarchy.

If that's the case, here is syntactically what I'm referring to:

foreach (var obj in employeeArray)
{
    Console.WriteLine("Employee ID: {0}", ((Employee)obj).empID);
    Console.WriteLine("Employee Wage: {0}", ((Employee)obj).empWage);
    Console.WriteLine();
}

Although casting will work for many cases, this kind of code is brittle since it relies on a bunch of assumptions, the biggest of which is that everything in your array is of type Employee. Rather than make the assumption, you can just have the compiler enforce this for you by using a generic list rather than a plain array. To do that your definition of the collection would be:

List<Employee> employeeArray = new List<Employee>();

One final technique you can use: C# has two operators used for casting that are quite robust: this is and as operators. The is operator will allow you to conditionally check whether something is a certain type and the as operator let's you attempt a cast but get a null value if the type doesn't match. Here are variations of your loop with both operators to give you a feel for how things might work:

Below I use is to verify type before accessing properties:

foreach (var obj in employeeArray)
{
    if (obj is Employee)
    {
        Console.WriteLine("Employee ID: {0}", obj.empID);
        Console.WriteLine("Employee Wage: {0}", obj.empWage);
        Console.WriteLine();
    }
}

In the below I use as to attempt the cast, but I check if it's null before attempting to access properties.

foreach (var obj in employeeArray)
{
    var emp = obj as Employee;
    if (emp != null )
    {
        Console.WriteLine("Employee ID: {0}", obj.empID);
        Console.WriteLine("Employee Wage: {0}", obj.empWage);
        Console.WriteLine();
    }
}

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