English 中文(简体)
是否可以在匿名职能中规定“这种”?
原标题:Is it possible to set "this" in anonymous function?

一、导 言

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 */);
最佳回答

<>第号

是的,如果《行动》是在可动用且受封锁约束的范围内建立的——但透明:无。

Pass in all needed information or make sure it s captured/available in the Action itself. There are other hacks like thread-locals, etc. Best avoided.

问题回答

由于职能略有变化,你可以取得预期的效果。

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" */);

Note: The anonymous function will only have access to public members however. If the anonymous function was defined within the class, it will have access to protected and private members as usual.

例如,

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签