Does it make sense to pass a “reference type” to a method as a parameter with 'ref' key? [duplicate]

混江龙づ霸主 提交于 2019-12-10 16:14:09

问题


Possible Duplicate:
C#: What is the use of “ref” for Reference-type variables?

Hi,

Does it make sense to pass a "reference type" to a method as a parameter with 'ref' key?

Or it is just nonsense as it is already a reference type but not a value type?

Thanks!


回答1:


It lets you change the reference variable itself, in addition to the object it's pointing to.

It makes sense if you think you might make the variable point to a different object (or to null) inside your method.

Otherwise, no.




回答2:


When passing a reference type as ref, you are passing the reference as a reference, and this might make sense. It means that the method can replace the reference, if it wishes to:

public void CallRef()
{
    string value = "Hello, world";
    DoSomethingWithRef(ref value);
    // Value is now "changed".
}

public void DoSomethingWithRef(ref string value) 
{
    value = "changed";
}



回答3:


If makes a difference, because it allows the method to change the instance your variable is pointing to.

In other words, you use it when you want to make your variable point to a different instance of your reference type.

private static void WithoutRef(string s)
{
    s = "abc";
}

private static void WithRef(ref string s)
{
    s = "abc";
}

private static void Main()
{
    string s = "123";

    WithoutRef(s);
    Console.WriteLine(s); // s remains "123"

    WithRef(ref s);
    Console.WriteLine(s); // s is now "abc"
}



回答4:


ref in C# allows you to modify the actual variable.

Check out this question - What is the use of "ref" for reference-type variables in C#? - including this example

Foo foo = new Foo("1");

void Bar(ref Foo y)
{
    y = new Foo("2");
}

Bar(ref foo);
// foo.Name == "2"



回答5:


It's not nonsense. When you do that, you're passing the reference by reference.

Example:

class X
{
     string y;
     void AssignString(ref string s)
    {
        s = "something";
    }
    void Z()
    {
        AssignString(ref this.y};
    }
}



回答6:


It does if you want the incoming variable that is being passed in to have its pointer changed.




回答7:


Consider the following code. What do you expect shall be the output from this program?

string s = "hello world";
Console.WriteLine(s);

foo(s);
Console.WriteLine(s);

bar(ref s);
Console.WriteLine(s);

void foo(string x)
{
    x = "foo";
}

void bar(ref string x)
{
    x = "bar";
}

The output is:

hello world
hello world
bar

When calling the method bar, you're passing the reference to string s by reference (instead of by value), which means that s will then change at the call site.



来源:https://stackoverflow.com/questions/5960778/does-it-make-sense-to-pass-a-reference-type-to-a-method-as-a-parameter-with-r

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