“ref” keyword and reference types [duplicate]

吃可爱长大的小学妹 提交于 2019-12-17 21:05:08

问题


someone in my team stumbled upon a peculiar use of the ref keyword on a reference type

class A { /* ... */ } 

class B
{    
    public void DoSomething(ref A myObject)
    {
       // ...
    }
}

Is there any reason someone sane would do such a thing? I can't find a use for this in C#


回答1:


Let

class A
{
    public string Blah { get; set; }
}

void Do (ref A a)
{
    a = new A { Blah = "Bar" };
}

then

A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (ref a);
Console.WriteLine(a.Blah); // Bar

But if just

void Do (A a)
{
    a = new A { Blah = "Bar" };
}

then

A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (a);
Console.WriteLine(a.Blah); // Foo



回答2:


Only if they want to change the reference to the object passed in as myObject to a different one.

public void DoSomething(ref A myObject)
{
   myObject = new A(); // The object in the calling function is now the new one 
}

Chances are this is not what they want to do and ref is not needed.




回答3:


The ref keyword is usefull if the method is supposed to change the reference stored in the variable passed to the method. If you do not use ref you can not change the reference only changes the object itself will be visible outside the method.

this.DoSomething(myObject);
// myObject will always point to the same instance here

this.DoSomething(ref myObject);
// myObject could potentially point to a completely new instance here



回答4:


There's nothing peculiar with this. You reference variables if you want to return several values from a method or just don't want to reassign the return value to the object you've passed in as an argument.

Like this:

int bar = 4;
foo(ref bar);

instead of:

int bar = 4;
bar = foo(bar);

Or if you want to retrieve several values:

int bar = 0;
string foobar = "";
foo(ref bar, ref foobar);


来源:https://stackoverflow.com/questions/4656184/ref-keyword-and-reference-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!