In "Captured Variables" how a variable is captured?
在“捕获变量”中,如何捕获一个变量?
What does that 'Captured' term stands for actually?
“捕获”一词到底代表什么?
Does it mean referencing a value type without getting the boxing involved?
它是否意味着在不涉及装箱的情况下引用值类型?
Thanks
谢谢
1 个解决方案
#1
7
Captured Variables generally refers to a variable captured with a closure (basically an inline function). To "capture" means that the inline function must "capture" a reference to a variable in the outer function. To do this, the C# compiler generates a inner class and passes the outer variable by reference into the inner class (which the inline function subsequently references). You can see this if you disassemble your code.
捕获的变量通常指用闭包捕获的变量(基本上是内联函数)。“捕获”意味着内联函数必须“捕获”外部函数中的变量的引用。为此,c#编译器生成一个内部类,并通过引用将外部变量传递给内部类(内联函数随后引用内部类)。如果对代码进行分解,您可以看到这一点。
Consider the following
考虑以下
void Main()
{
string s = "hello";
Action a = delegate
{
Debug.WriteLine(s);
};
s = "hello2";
a();
}
In the example above, the string variable s is captured by the inline Action a.
在上面的示例中,字符串变量s由内联动作a捕获。
Under the hood, the C# compiler will create an inner class, which Action a references to capture the value of variable s. It's important to note that string s is passed by reference to the Action a, so the action will actually print out "hello2", not "hello". This can produce unintended side effects if not understood clearly, and is referred to as "accessing a modified closure".
在引擎盖下,c#编译器将创建一个内部类,该类操作一个引用来捕获变量s的值。重要的是要注意,字符串s是通过对动作a的引用传递的,因此该操作实际上将输出“hello2”,而不是“hello”。如果理解不清楚,这可能产生意想不到的副作用,并被称为“访问修改过的闭包”。
#1
7
Captured Variables generally refers to a variable captured with a closure (basically an inline function). To "capture" means that the inline function must "capture" a reference to a variable in the outer function. To do this, the C# compiler generates a inner class and passes the outer variable by reference into the inner class (which the inline function subsequently references). You can see this if you disassemble your code.
捕获的变量通常指用闭包捕获的变量(基本上是内联函数)。“捕获”意味着内联函数必须“捕获”外部函数中的变量的引用。为此,c#编译器生成一个内部类,并通过引用将外部变量传递给内部类(内联函数随后引用内部类)。如果对代码进行分解,您可以看到这一点。
Consider the following
考虑以下
void Main()
{
string s = "hello";
Action a = delegate
{
Debug.WriteLine(s);
};
s = "hello2";
a();
}
In the example above, the string variable s is captured by the inline Action a.
在上面的示例中,字符串变量s由内联动作a捕获。
Under the hood, the C# compiler will create an inner class, which Action a references to capture the value of variable s. It's important to note that string s is passed by reference to the Action a, so the action will actually print out "hello2", not "hello". This can produce unintended side effects if not understood clearly, and is referred to as "accessing a modified closure".
在引擎盖下,c#编译器将创建一个内部类,该类操作一个引用来捕获变量s的值。重要的是要注意,字符串s是通过对动作a的引用传递的,因此该操作实际上将输出“hello2”,而不是“hello”。如果理解不清楚,这可能产生意想不到的副作用,并被称为“访问修改过的闭包”。