【问题标题】:Scope of the object and manipulation on the object in term of reference type对象的范围和在引用类型方面对对象的操作
【发布时间】:2014-01-06 16:38:43
【问题描述】:

请查看以下代码。我无法纠正当我们创建名为 objStudent1 的类 Student 的对象时,我们设置了两个值 name 和 roll number 现在它包含该值

  • 姓名:学生2
  • 卷号:222

现在我们将这个对象作为参数传递给一个名为ChangeName的函数,这里参数的名称是objStudent2,我们再次设置相同的值,现在它保存了值

  • 姓名:学生3
  • 卷号:333

然后我们将objStudent2对象设置为空值。

在执行完整的函数ChangeName 后,它会打印在ChangeName 函数中设置的值,这些值是从对象objStudent1 打印出来的。

对数据成员所做的修改正在反映,但 null 并未反映在同一对象上的函数之外。

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Student objStudent1 = new Student();
            objStudent1.Name = "Student2";
            objStudent1.RollNumber = 222;
            ChangeName(objStudent1);
            System.Console.WriteLine("Name-" + objStudent1.Name);
            System.Console.WriteLine("Roll Number-" + objStudent1.RollNumber);
            System.Console.Read();
        }

        private static void ChangeName(Student objStudent2)
        {
            objStudent2.Name = "Student3";
            objStudent2.RollNumber = 333;
            objStudent2 = null;
        }
    }

    class Student
    {
        public string Name = "Student1";
        int _RollNumber = 111;

        public int RollNumber
        {
            get { return _RollNumber; }
            set { _RollNumber = value; }
        }
    }
}

请告诉我这里发生了什么!

我完全糊涂了!

【问题讨论】:

    标签: c# .net oop object


    【解决方案1】:

    请注意,objStudent1 和 objStudent2 都是对同一个对象的引用。即使您将 objStudent2 引用清空,您仍然拥有 objStudent1 引用。物体还在。然后使用 objStudent1 引用打印出成员。

    【讨论】:

      【解决方案2】:

      您的引用变量只不过是对您的数据实际所在的某个内存位置的引用。

      例如:

      // this allocates some memory space for your instance/object
       new Student();
      
      //this line also does allocates some memory space but the difference is it has got some reference/agent to access that memory location.
      Subject obj = new Student();
      
      //This block has obj and obj1. Both obj and obj1 acts almost like agent/broker to that specific memory location. The line 2 does not mean it is separate object/ memory location but its just another reference to the same memory location.
      Subject obj = new Student();
      Subject obj1 = obj;
      
      //In 3rd line of this block, you are not nullifying the memory location but you are just trying to nullify the reference alone.It does not make any disturbance to that memory location and its contents.
      Subject obj = new Student();
      Subject obj1 = obj;
      Obj1=null;
      
      // This still will work because this reference to that memory location is not nullified.
      Obj.getXXXX(); 
      

      希望这有帮助!

      【讨论】:

        猜你喜欢
        • 2016-05-28
        • 1970-01-01
        • 1970-01-01
        • 2012-04-14
        • 2016-04-19
        • 1970-01-01
        • 2022-07-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多