C# 람다(Lambda)에서 변수 캡처 방식
C# 람다 함수 내에서의 변수 캡처 방식을 한번 살펴볼까요?
예제는 다음의 글에 있는 것으로,
Action 대리자
; https://learn.microsoft.com/en-us/dotnet/api/system.action
가져다 쓰겠습니다.
using System;
using System.Windows.Forms;
public class Name
{
private string instanceName;
public Name(string name)
{
this.instanceName = name;
}
public void DisplayToWindow()
{
MessageBox.Show(this.instanceName);
}
}
public class LambdaExpression
{
public static void Main()
{
Name testName = new Name("Koani");
Action showMethod = () => testName.DisplayToWindow();
showMethod();
}
}
C# 컴파일러는 이런 구문을 만나면 람다 함수내에 캡처되는 변수와 람다 메서드의 코드를 담은 클래스를 컴파일 시에 만들어 둡니다. 가령 다음과 같은 식입니다.
public class [임시클래스]
{
Name _name;
public void _f()
{
_name.DisplayToWindow(); // showMethod에 넣었던 Lambda 메서드 body
}
}
그리곤 원래의 소스코드를 다음과 같이 바꿉니다.
public static void Main()
{
[임시클래스] _var = new [임시클래스]();
_var._name = new Name("Koani");
Action showMethod = _var._f;
showMethod();
}
간단하지요? ^^
이 원칙에 기반해서 C#의 변수 캡처에 대한 주의 사항으로 잘 나오는 예제를 한번 볼까요?
// http://stackoverflow.com/questions/451779/how-to-tell-a-lambda-function-to-capture-a-copy-instead-of-a-reference-in-c
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 10; ++i)
{
actions.Add(() => Console.WriteLine(i));
}
foreach (Action a in actions)
{
a();
}
// 기대하던 출력: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
// 실제 출력: 10, 10, 10, 10, 10, 10, 10, 10, 10, 10
}
}
위의 코드를 작성한 개발자의 기대값과 실제값은 다릅니다. 왜냐하면, C# 컴파일러는 i 값에 대한 변수를 다음과 같이 임시 생성한 클래스의 변수로 대체해 버리기 때문입니다.
// http://stackoverflow.com/questions/451779/how-to-tell-a-lambda-function-to-capture-a-copy-instead-of-a-reference-in-c
using System;
using System.Collections.Generic;
public class [임시클래스]
{
public int _i;
public void _f()
{
Console.WriteLine(_i);
}
}
class Program
{
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
[임시클래스] _var = new [임시클래스]();
for (_var._i = 0; _var._i < 10; ++_var._i)
{
actions.Add(_var._f);
}
foreach (Action a in actions)
{
a();
}
}
}
만약, 개발자가 원래 의도했던 대로 나오게 하고 싶다면 어떻게 해야 할까요? 그럼 다음과 같이 해야 합니다.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 10; ++i)
{
int v = i;
actions.Add(() => Console.WriteLine(v));
}
foreach (Action a in actions)
{
a();
}
}
}
이렇게 되면 C# 컴파일러는 i가 아닌 v 변수값을 캡처하기 위해 다음과 같은 식으로 for 루프 내에서 임시클래스를 생성하게 됩니다.
// http://stackoverflow.com/questions/451779/how-to-tell-a-lambda-function-to-capture-a-copy-instead-of-a-reference-in-c
using System;
using System.Collections.Generic;
public class [임시클래스]
{
public int _v;
public void _f()
{
Console.WriteLine(_i);
}
}
class Program
{
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 10; ++i)
{
[임시클래스] _var = new [임시클래스]();
_var._v = i;
actions.Add(_var._f);
}
foreach (Action a in actions)
{
a();
}
}
}
대충 감이 오시나요? ^^ 결국, "마법은 없습니다."
이제 C# 공식 문서의 내용을 보면,
Lambda Expressions (C# Programming Guide)
; https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions
람다 함수 내에서의 변수 제약이 이해가 됩니다.
- A variable that is captured will not be garbage-collected until the delegate that references it becomes eligible for garbage collection.
- Variables introduced within a lambda expression are not visible in the outer method.
- A lambda expression cannot directly capture a ref or out parameter from an enclosing method.
- A return statement in a lambda expression does not cause the enclosing method to return.
- A lambda expression cannot contain a goto statement, break statement, or continue statement that is inside the lambda function if the jump statement’s target is outside the block. It is also an error to have a jump statement outside the lambda function block if the target is inside the block.
참고로, 자바의 변수 캡처 처리 방식과 비교해 보고 싶다면 다음의 글을 참고하세요.
자바 8과 C#의 람다(Lambda) 지원에 대한 비교
; https://www.sysnet.pe.kr/2/0/1685
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]