문제
따라서 Foreach Loop을 사용하여 반복하고 있고 내부에 목록에서 반복 된 객체의 인수를 가져 오는 기능이 있고 그 값이 다른 것으로 설정했다고 가정합니다. 왜 내가 사용하거나 심판 할 필요가 없습니까? 나는 그것이 당신이 사용하지 않거나 참조하지 않은 경우에만 가치로 전달되었다고 생각했습니다 .... 나는 당신이 메소드에서 수익을하기 전에 값을 설정해야하기 전에 변수를 초기화해야한다는 것을 알고 있습니다.
목록을 통해 반복하는 것 같고 실제로 참조로 통과 된 객체를 전달하는 것 같습니다. 다음 예를 고려하십시오.
예시
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 내부 : 1 ::
WithoutRef SetFoo 게시물 : 1 WithoutRef
setfoo pre : 1 :: WithoutRef setfoo
내부 : 1 :: WithoutRef :: Withref
setfoo post : 1 withoutref :: Withrefsetfoo pre : 2 setfoo 내부 : 2 ::
WithoutRef SetFoo 게시물 : 2 WithoutRef
setfoo pre : 2 :: WithoutRef setfoo
내부 : 2 :: WithoutRef :: Withref
setfoo post : 2 withoutref :: Withrefseti pre : 0 seti : 2 setipost : 0
setRefi pre : 0 setrefi 내부 : 3
SetRefi 게시물 : 3
나는 정수 예제를 가진 심판을 이해하지만 위의 foo 객체 반복 예제는 아닙니다.
감사!
해결책
그만큼 참조 가치에 따라 통과됩니다. 따라서 메소드는 여전히 객체의 내용을 변경할 수 있으며 변수가 참조하는 객체를 변경할 수 없습니다.
보다 매개 변수 통과에 관한 내 기사 더 많은 정보를 얻으려면 내 기사와 함께 참조 유형 및 값 유형.