【问题标题】:Send an instance from a class is same as send it by reference [duplicate]从类发送实例与通过引用发送实例相同[重复]
【发布时间】:2015-02-22 08:25:34
【问题描述】:

正如标题所说“从一个类中发送一个实例是否与通过 ref 发送它具有相同的效果”

例如

FillStudentInformation(student);

效果和

一样
FillStudentInformation(ref student);       

我是否期望这两个实例都将被此调用以相同的方式更改。

注意:FillStudentUnformation 是一个 void 方法

【问题讨论】:

标签: c# oop


【解决方案1】:

主要区别在于,如果您在方法内部执行类似操作:

student = new Student();

在第二种情况下,您也将在方法之外更改学生对象(不是在第一种情况下)。

使用类似的东西:

student.Name = 'John Doe';

两者都一样。

但是,您应该尽量避免引用,因为它会导致更多的副作用和更低的可测试性。

【讨论】:

    【解决方案2】:

    如果我假设 Student 是类的对象(引用类型),你不应该期望相同的行为,因为两者是不同的东西。这也取决于你在方法中做了什么。

    第一种方法

    void Main()
    {
       Student student = new Student();
       FillStudentUnformation(student);
       Console.WriteLine(student.Name); // Here you will not get name
       FillStudentUnformationRef(ref student);
       Console.WriteLine(student.Name);    // you will see name you have set inside method.
    }
    
    vodi FillStudentUnformation(Student student)
    {
       //If here if you do 
       student = new Student(); 
       student.Name = "test"; // This will not reflect outside.
    }
    
    vodi FillStudentUnformationRef(ref Student student)
    {
       //If here if you do 
       student = new Student(); 
       student.Name = "test ref"; // This will not reflect outside.
    }
    

    所以当我们将引用类型传递给方法时,它会将引用的副本传递给该变量。因此,当您使用 new 更新该变量时,它将更新该变量引用而不是实际引用。

    在第二种方法中,它将传递实际引用,因此当您更新它会影响对象的实际引用。

    更多信息:http://msdn.microsoft.com/en-IN/library/s6938f28.aspx

    【讨论】:

    • 为什么一开始我不会得到名字?我需要了解一下
    • 你是对的,但我需要明白为什么?正如我认为的那样,你们都发送了我们所在的当前地址
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多