You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# OOP中对象数组问题:已声明对象名称被覆盖无法修复

解决C# OOP中对象数组属性被覆盖的问题

嘿,我太懂这种踩坑的憋屈感了!你这个问题的根源其实一眼就能揪出来——你把Student类里的所有成员变量都声明成了static,这直接导致所有对象共享同一套属性值,新对象自然会把之前的覆盖掉。

问题拆解

static关键字修饰的成员是类级别的,不属于任何单个对象。也就是说,不管你创建多少个Student实例,它们都共用同一个name、DOB、ID和height变量。每次你给新对象赋值,本质上都是在修改这个共享的变量,所以之前对象的属性就被冲掉了。

修正后的代码

把所有成员变量的static关键字去掉,让每个Student对象拥有自己独立的属性副本:

using System;

namespace OOP { 
    class Student { 
        // 移除static,每个对象独立持有这些属性
        private string name; 
        private DateTime DOB; 
        private int ID; 
        private double height; 

        // 建议添加构造函数,方便初始化对象属性
        public Student(string studentName, DateTime dateOfBirth, int studentId, double studentHeight)
        {
            name = studentName;
            DOB = dateOfBirth;
            ID = studentId;
            height = studentHeight;
        }

        // 添加属性访问器,方便外部获取/修改私有字段
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Student[] students = new Student[2];
            students[0] = new Student("Alice", new DateTime(2000, 5, 10), 1001, 165.3);
            students[1] = new Student("Bob", new DateTime(2001, 3, 15), 1002, 178.0);

            Console.WriteLine(students[0].Name); // 输出 Alice
            Console.WriteLine(students[1].Name); // 输出 Bob,不会被覆盖啦
        }
    }
}

额外提示

只有当你需要让所有对象共享某个值的时候(比如统计当前创建了多少个Student对象的计数器),才应该使用static成员。而像姓名、生日这种每个学生独有的属性,必须是实例级别的,绝对不能加static。

内容的提问来源于stack exchange,提问作者user9674611

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:24:06