开发学院软件开发C语言 C#里,派生类的方法里的匿名delegate调用基类的方... 阅读

C#里,派生类的方法里的匿名delegate调用基类的方法会产生无法验证的代码

 2009-06-04 08:30:17 来源:WEB开发网   
核心提示: Unified C# 3.0 Specification中, 引用7.14.4 Outer variables Any local variable, value parameter, or parameter array whose scope includes the lambda-e

Unified C# 3.0 Specification中,

引用

7.14.4 Outer variables
Any local variable, value parameter, or parameter array whose scope includes the lambda-expression or anonymous-method-expression is called an outer variable of the anonymous function. In an instance function member of a class, the this value is considered a value parameter and is an outer variable of any anonymous function contained within the function member.

7.14.4.1 Captured outer variables
When an outer variable is referenced by an anonymous function, the outer variable is said to have been captured by the anonymous function. Ordinarily, the lifetime of a local variable is limited to execution of the block or statement with which it is associated (§5.1.7). However, the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.

不同语言为闭包分配空间的具体方式不同。C#中,编译器会将逃逸变量提升为成员变量,并将匿名delegate提升为一个成员方法——不过并不是提升到原本的类中,而是一个由编译器构造的私有内部类中。上面的代码,会被编译器变成类似以下的形式:

引用

C#代码   

public class Bravo : Alpha {

    public override void Blah() {
        Console.WriteLine("Bravo.Blah");
        base.Blah();
    }
    
    // compiler generated inner class
    private class __locals {
        public int __x;
        public Bravo __this;
        public void __method() {
            this.__this.blah();
            // on the next line, no such "__nonvirtual__" in C#
            __nonvirtual__ ((Alpha)this.__this).Blah());
            Console.WriteLine(this.__x);
        }
    }
    
    public void Charlie() {
        __locals locals = new __locals();
        locals.__x = 123;
        locals.__this = this;
        D d = new D(locals.__method);
        d();
    }
}

上一页  1 2 3 4 5 6  下一页

Tags:派生 方法 匿名

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接