1

因此,如果我使用 foreach 循环进行迭代,并且内部有一个函数,该函数接受从列表中迭代的对象的参数,并假设我将其值设置为不同。为什么我不必使用 out 或 ref ?我认为它只有在你没有使用 out 或 ref 时才通过值传递。我知道一个 ref 你必须在之前初始化变量并且 out 你只需要在从方法返回之前设置它的值。

看起来如果你遍历一个列表并在其实际通过引用传递的对象中传递一个对象。考虑以下示例。

例子

class Program
    {
        static void Main(string[] args)
        {

            List<Foo> list = new List<Foo>();
            list.Add(new Foo() { Bar = "1" });
            list.Add(new Foo() { Bar = "2" });



            foreach (var f in list)
            {
                Foo f2 = f; 
                Console.WriteLine("SetFoo Pre: " + f2.Bar);
                SetFoo(f2);
                Console.WriteLine("SetFoo Post: " + f2.Bar);

                Console.WriteLine("SetFooRef Pre: " + f2.Bar);
                SetFooRef(ref f2);
                Console.WriteLine("SetFooRef Post: " + f2.Bar);
                Console.WriteLine("");
            }




            Console.WriteLine("");

            int i = 0;
            // Not using ref keyword
            Console.WriteLine("SetI Pre: " + i);
            SetI(i);
            Console.WriteLine("SetI Post: " + i);

            // Using ref keyword
            Console.WriteLine("SetRefI Pre: " + i);
            SetRefI(ref i);
            Console.WriteLine("SetRefI Post: " + i);
        }


        private static void SetRefI(ref int i)
        {
            i = 3;
            Console.WriteLine("SetRefI Inside: " + i);
        }

        private static void SetI(int i)
        {
            i = 2;
            Console.WriteLine("SetI Inside: " + i);
        }

        private static void SetFooRef(ref Foo f)
        {
            f.Bar = String.Format("{0} :: {1}", f.Bar, "WithRef");
            Console.WriteLine("SetFooRef Inside: " + f.Bar);
        }

        private static void SetFoo(Foo f)
        {
            f.Bar = String.Format("{0} :: {1}", f.Bar, "WithoutRef");
            Console.WriteLine("SetFoo Inside: " + f.Bar);
        }
    }


    class Foo
    {
        public string Bar { get; set; }
    }

输出:

SetFoo Pre: 1 SetFoo Inside: 1 ::
WithoutRef SetFoo Post: 1 WithoutRef
SetFoo Pre: 1 :: WithoutRef SetFoo
Inside: 1 :: WithoutRef :: WithRef
SetFoo Post: 1 WithoutRef :: WithRef

SetFoo Pre: 2 SetFoo Inside: 2 ::
WithoutRef SetFoo Post: 2 WithoutRef
SetFoo Pre: 2 :: WithoutRef SetFoo
Inside: 2 :: WithoutRef :: WithRef
SetFoo Post: 2 WithoutRef :: WithRef

SetI Pre: 0 SetI Inside: 2 SetIPost: 0

SetRefI Pre: 0 SetRefI Inside: 3
SetRefI Post: 3

我理解带有整数示例的 ref,但不理解上面的 Foo 对象迭代示例。

谢谢!

4

1 回答 1

12

引用是按值传递的。所以该方法仍然可以改变对象的内容,只是不能改变你的变量引用的对象。

有关更多信息,请参阅我关于参数传递的文章,以及关于引用类型和值类型的文章。

于 2009-10-29T15:07:34.293 回答