对象的范围和对象的引用类型的操作

时间:2013-12-18 13:13:09

标签: c# .net oop object

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

  • 姓名:student2
  • 卷号:222

现在我们将此对象传递给名为ChangeName的函数作为参数,此处参数的名称为objStudent2,我们再次设置相同的值,现在它保存值

  • 姓名:student3
  • 卷号: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; }
        }
    }
}

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

我完全糊涂了!

2 个答案:

答案 0 :(得分:0)

请注意,objStudent1和objStudent2都是对同一对象的引用。即使在将objStudent2引用置空后,仍然有objStudent1引用。对象仍在那里。然后使用objStudent1引用打印出成员。

答案 1 :(得分:0)

您的引用变量只不过是对数据实际驻留的某些内存位置的引用。

例如:

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

希望这是有帮助的!