类如何可以作为引用类型 [英] how class can be a reference type

查看:60
本文介绍了类如何可以作为引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当类是引用类型时,不同实例如何为类的同一成员具有不同的值



因为类是引用类型类的实例只指向类中成员或变量的内存位置。然后,类的不同实例如何具有类成员或变量的不同副本

how different instances can have different values for the same member of a class when a class is a reference type

Since class is a reference type the instances of class point only to the memory location of the members or variables in the class.Then how different instances of class can have different copies of class members or variables

推荐答案

简短回答是不同的实例引用不同的内存位置。



长答案: http://msdn.microsoft.com/en-us/magazine/cc301569.aspx [ ^ ]
Short answer is different instances reference different memory locations.

Long answer: http://msdn.microsoft.com/en-us/magazine/cc301569.aspx[^]


由于类是引用类型,类的实例仅指向内存位置类中的成员或变量。然后,类的不同实例如何具有不同的类成员副本o r变量



因为每个实例都指向由 new 声明。


我在这里误读了你的问题是我的更新解决方案。



当你创建一个类的实例时 new 关键字为该实例创建一个新实例和新内存块,因此它可以为该类的同一成员提供不同的值。



详细信息
I misread your question here is my updated solution.

when you create an instance of the class with new keyword it creates a new instance and new memory block for that instance hence it can have different values for the same member of the class.

in detail
class Student
{
 public string StudentName = string.Empty;
 public int Age = 0;
}

class StudentManager
{
  public void ManageStudents()
  {
    Student student1 = new Student(); // Creating Instance1;
    
    student1.Name = "Student 1"; 
    
    Student student2 = new Student(); // Creating Instance2;
    student2 .Name = "Student 2"; // Instance 2 created 

    //Instance1 and Instance2 are different because we create 2 different memory block for the student class using the new Keyword
    //Now see the magic of Reference type
    int age = 10;
    Console.WriteLine(student1.Age);    
    ChangeStudentName(student1,age);  
    Console.WriteLine(student1.Age);     
  }
 
  private ChangeStudentAge(Student student,int newAge)
  {
     student.Age= newAge;
     newAge = 100;
    //the variable student is local to this method but any changes made to the student instance will get effected on the original student1 instance inside the 'ManageStudents' method. but any changes made to the 'newAge' int variable does not change the age variable defined in the ManageStudents method. 

   //Because student is reference type object and int is a value type object
  }
}


这篇关于类如何可以作为引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆