代码之家  ›  专栏  ›  技术社区  ›  mpen

是否可以在匿名函数中设置“this”?

  •  4
  • mpen  · 技术社区  · 14 年前

    我有一个函数,

    public SharpQuery Each(Action<int, HtmlNode> function)
    {
        for (int i = 0; i < _context.Count; ++i)
            function(i, _context[i]);
        return this;
    }
    

    Action<int, HtmlNode> function ?

    例如,

    sharpQuery.Each((i, node) => /* `this` refers to an HtmlNode here */);
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   user166390 user166390    14 年前

    不。

    好吧,是的,如果操作是在这样一个范围内创建的,其中“this”是可用的,并且绑定在一个闭包中——但是透明地:不。

        2
  •  5
  •   Jeff Mercado    14 年前

    只要稍微改变一下功能,就可以达到预期的效果。

    public SharpQuery Each(Action<MyObject, int, HtmlNode> function)
    {
        for (int i = 0; i < _context.Count; ++i)
            function(this, i, _context[i]);
        return this;
    }
    

    然后你可以这样写你的函数调用:

    sharpQuery.Each((self, i, node) => /* do something with `self` which is "this" */);
    

    注意:匿名函数只能访问公共成员。如果匿名函数是在类中定义的,它将像往常一样访问受保护和私有成员。

    class MyObject
    {
        public MyObject(int i)
        {
            this.Number = i;
        }
    
        public int Number { get; private set; }
        private int NumberPlus { get { return Number + 1; } }
    
        public void DoAction(Action<MyObject> action)
        {
            action(this);
        }
    
        public void PrintNumberPlus()
        {
            DoAction(self => Console.WriteLine(self.NumberPlus));  // has access to private `NumberPlus`
        }
    }
    
    MyObject obj = new MyObject(20);
    obj.DoAction(self => Console.WriteLine(self.Number));     // ok
    obj.PrintNumberPlus();                                    // ok
    obj.DoAction(self => Console.WriteLine(self.NumberPlus)); // error