6

我团队中的某个人偶然发现了 ref 关键字在引用类型上的特殊用法

class A { /* ... */ } 

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

有理智的人会做这样的事吗?我在 C# 中找不到它的用途

4

4 回答 4

16

只有当他们想要将传入的对象的引用myObject更改为不同的引用时。

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

这很可能不是他们想要做的,ref也不需要。

于 2011-01-11T09:43:14.147 回答
13

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

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

然后

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

但如果只是

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

然后

A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (a);
Console.WriteLine(a.Blah); // Foo
于 2011-01-11T09:48:56.373 回答
0

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);
于 2011-01-11T09:56:53.880 回答
0

如果该方法应该更改存储在传递给该方法的变量中的引用,则该ref关键字很有用。如果不使用ref不能更改引用,只能更改对象本身在方法之外可见。

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
于 2011-01-11T09:51:50.973 回答