开发者

C# ref question again?

开发者 https://www.devze.com 2022-12-26 20:46 出处:网络
class Foo { public int A 开发者_高级运维{ get; set; } } class Program { static void Main(string[] args)
 class Foo
    {
        public int A 开发者_高级运维{ get; set; }
    }

class Program
{
    static void Main(string[] args)
    {
        var f = new Foo();
        var ff = f;

        Console.WriteLine(f.GetHashCode());
        Console.WriteLine(ff.GetHashCode());

        FooFoo(ref f);
        BarBar(f);
    }

    private static void BarBar(Foo f)
    {
        Console.WriteLine(f.GetHashCode());
    }

    private static void FooFoo(ref Foo f)
    {
        Console.WriteLine(f.GetHashCode());
    }
}

OUTPUT:

58225482
58225482
58225482
58225482

What is the difference between FooFoo and BarBar?


No effective difference in this case.

The point of ref is not to pass a reference to an object, it is to pass a reference to a variable.

Consider the following change:

private static void BarBar(Foo f)
{
    Console.WriteLine(f.GetHashCode());
    f = new Foo();
}

private static void FooFoo(ref Foo f)
{
    Console.WriteLine(f.GetHashCode());
    f = new Foo();
}

In this case, the FooFoo's change will also change the f variable in the Main method, but the BarBar method is only changing a local variable.

All reference types are passed as reference types in any case, you cannot change that. The only point to ref is to allow the called method to change the variable it is being passed.

0

精彩评论

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

关注公众号