C# objects by Ref

后端 未结 8 819
清歌不尽
清歌不尽 2021-01-27 12:23

If one passes an object to a method using the \'Ref\' keyword then what is the difference with passing it without the ref keyword?

Because both yield the same result, th

8条回答
  •  逝去的感伤
    2021-01-27 12:56

    Try changing your two Student methods to:

    public static void SetStudent( ref Student student )
    {
        student = new Student();
        student.Age = 16;
        student.Name = "StudentY";
    }
    
    public static void AnotherStudent( Student studenta )
    {
        studenta = new Student();
        studenta.Age = 12;
        studenta.Name = "StudentX";
    }
    

    The call to SetStudent will now change your static student variable to reference a new instance because it is passed as a ref. The call to AnotherStudent won't change the reference.

提交回复
热议问题