简体   繁体   中英

Why is Visual studio adding “ref” to value types when refactoring into methods?

I don't understand a decision that Visual Studio Express 2013 makes when running the "Extract Method" refactoring. Consider the following code:

public struct Foo
{
    private readonly int x, y;
    public int X { get { return x; } }
    public int Y { get { return y; } }

    public Foo(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

class Test
{
    static void Main()
    {
        Foo a = new Foo(1, 2);
        Foo b = new Foo(3, 4);
        Console.WriteLine(a);
        Console.WriteLine(a + "" + b);
    }
}

If I highlight the first Console.WriteLine call and run the Extract Method refactoring, extracting a method called OneParameter , then do the same with the second call extracting a method called TwoParameters , I end up with this code:

class Test
{
    static void Main()
    {
        Foo a = new Foo(1, 2);
        Foo b = new Foo(3, 4);
        OneParameter(a);
        TwoParameters(ref a, ref b);
    }

    static Foo OneParameter(Foo a)
    {
        Console.WriteLine(a);
        return a;
    }

    static void TwoParameters(ref Foo a, ref Foo b)
    {
        Console.WriteLine(a + "" + b);
    }
}

Why does the two-parameter method have ref parameters, but not the one-parameter method? What is the point of using ref here?

Also, why does the one-parameter method return Foo?

Both the return and the two refs happen in case the struct is mutable and modified. VS 2013 doesn't really do any analysis of either the struct type for immutability, or the selected code for mutating operations. It doesn't happen for primitives/Guid/etc simply because there is a hard-coded list of value types in the framework that are known to be immutable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM