在 C# 中,如何获取数组内对象的属性?

发布于 2024-10-25 08:47:18 字数 1000 浏览 1 评论 0原文

我在尝试使用以下方法引用已插入数组的对象的属性时遇到问题。

    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);

    }

我想以某种可读格式打印出该数组中的信息,但我不知道如何引用 empWage 或 empID。理想情况下,我想使用某种 foreach 循环,如下所示:

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

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();
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅沫记忆 2024-11-01 08:47:18

您几乎已经完成了:

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

更新:

如果 employeeArray 的类型为 object[],则无法直接引用类 Employee 中定义的属性

如何修复它:

使用 List 代替 object[],例如:

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

您还需要更改向列表添加项目的方式:

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

最后,CreateEmployee 的返回类型应为 Employee(而不是 object)。

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).

伤痕我心 2024-11-01 08:47:18

对您问题的最快答案是您可以将对象强制转换到数组中。

((Employee)obj).empID

您还没有展示如何定义数组;如果它是 Employee 数组,那么您可以安全地在 foreach 中进行强制转换,但由于您收到错误,我猜测您的数组可能是对象或继承层次结构中更高的对象。

如果是这样的话,从语法上讲,我指的是:

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

虽然转换适用于许多情况,但这种代码很脆弱,因为它依赖于一堆假设,其中最大的假设是数组中的所有内容都是类型员工。您可以让编译器通过使用通用列表而不是普通数组来强制执行此假设,而不是做出假设。为此,您对集合的定义将是:

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

您可以使用的最后一种技术:C# 有两个用于强制转换的运算符,它们非常强大:此 as 运算符。 is 运算符将允许您有条件地检查某些内容是否为特定类型,而 as 运算符可让您尝试进行强制转换,但如果类型不匹配,则会获取 null 值。以下是使用两个运算符的循环变体,让您了解事情的工作原理:

下面我使用 is 在访问属性之前验证类型:

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();
    }
}

下面我使用 as > 尝试强制转换,但我在尝试访问属性之前检查它是否为空。

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 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();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文