引用类型仍然需要通过ref?

use*_*677 5 c#

请考虑以下代码(为简单起见,我没有遵循任何C#编码规则).

public class Professor
{
    public string _Name;

    public Professor(){}

    public Professor(string name)
    {
        _Name=name;
    }

    public void Display()
    {
        Console.WriteLine("Name={0}",_Name);
    }
}

public class Example
{
    static int Main(string[] args)
    {
        Professor david = new Professor("David");

        Console.WriteLine("\nBefore calling the method ProfessorDetails().. ");
        david.Display();
        ProfessorDetails(david);
        Console.WriteLine("\nAfter calling the method ProfessorDetails()..");
        david. Display();
    }

    static void ProfessorDetails(Professor p)
    {
        //change in the name  here is reflected 
        p._Name="Flower";

        //Why  Caller unable to see this assignment 
        p=new Professor("Jon");
    }
}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,输出是:

在调用方法之前,教授Details()......

姓名=大卫

在调用方法ProfessorDetails()之后......

名字=花

通话 p=new Professor("Jon");ProfessorDetails(Professor p)是无效的,即使它是引用类型.为什么我仍然需要使用ref关键字来获得所需的结果?

Ed *_* S. 34

一切都是通过C#中的值传递的.但是,当您传递引用类型时,引用本身将按传递,即传递原始引用的副本.因此,您可以更改引用副本指向的对象的状态,但是如果为引用分配新值,则只更改副本指向的内容,而不是原始引用.

当您使用'ref'关键字时,它告诉编译器传递原始引用,而不是副本,因此您可以修改引用指向函数内部的内容.但是,对此的需求通常很少,并且最常用于需要从方法返回多个值时.

一个例子:

class Foo
{
    int ID { get; set; }

    public Foo( int id )
    {
        ID = id;        
    }
}

void Main( )
{
    Foo f = new Foo( 1 );
    Console.WriteLine( f.ID );  // prints "1"
    ChangeId( f );
    Console.WriteLine( f.ID );  // prints "5"
    ChangeRef( f );
    Console.WriteLine( f.ID );  // still prints "5", only changed what the copy was pointing to
}

static void ChangeId( Foo f )
{
    f.ID = 5;
}

static void ChangeRef( Foo f )
{
    f = new Foo( 10 );
}
Run Code Online (Sandbox Code Playgroud)