有没有一种方法可以让我内联,而不是在其他功能?

分离它的委托任务

原始编码:

    private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
    {            
        System.Threading.ThreadPool.QueueUserWorkItem((o) => Attach());
    }

    void Attach() // I want to inline this function on FileOk event
    {

        if (this.InvokeRequired)
        {
            this.Invoke(new Action(Attach));
        }
        else
        {
            // attaching routine here
        }
    }

我希望它是这样的(没有必要创建一个单独的函数):

    private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
    {

        Action attach = delegate
        {
            if (this.InvokeRequired)
            {
                // but it has compilation here
                // "Use of unassigned local variable 'attach'"
                this.Invoke(new Action(attach)); 
            }
            else
            {
                // attaching routine here
            }
        };

        System.Threading.ThreadPool.QueueUserWorkItem((o) => attach());
    }
有帮助吗?

解决方案

我认为这将工作:

private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
{

    Action attach = null;
    attach = delegate
    {
        if (this.InvokeRequired)
        {
            // since we assigned null, we'll be ok, and the automatic
            // closure generated by the compiler will make sure the value is here when
            // we need it.
            this.Invoke(new Action(attach)); 
        }
        else
        {
            // attaching routine here
        }
    };

    System.Threading.ThreadPool.QueueUserWorkItem((o) => attach());
}

所有你需要做的是赋值声明匿名方法前行到“连接”(空作品)。我认为前者更容易一点,虽然理解。

其他提示

在获得“使用未赋值的变量”错误的原因是因为编译器实际上生成代码的方式。当您使用委托{}语法编译器为您创建一个真正的方法。因为你在你委托引用附字段,编译器试图将局部变量attach传递给生成委托方法。

以下是大致翻译代码,这应有助于更清楚:

private void ofdAttachment_FileOk(object sender, CancelEventArgs e)
{

    Action attach = _b<>_1( attach );

    System.Threading.ThreadPool.QueueUserWorkItem((o) => attach());
}

private Action _b<>_1( Action attach )
{
    if (this.InvokeRequired)
    {
        // but it has compilation here
        // "Use of unassigned local variable 'attach'"
        this.Invoke(new Action(attach)); 
    }
    else
    {
        // attaching routine here
    }
}

请注意,它使附加字段到_b <> _ 1种方法它初始化之前。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top