开发者

"ref" keyword and reference types [duplicate]

This question already has answers here: 开发者_开发百科 What is the use of "ref" for reference-type variables in C#? (10 answers) Closed 9 years ago.

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#


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.


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


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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜