在Property的getter for .Net 2.0中调用不带Func

时间:2012-02-22 14:37:30

标签: c# .net invoke getter invokerequired

我想在getter中使用Invoke,如何在使用.Net 2.0时使用它。 4.0?对于.Net> 2.0我们可以使用Func和什么替代.Net 2.0?

以下是.Net 4.0(来自link

的示例
public ApplicationViewModel SelectedApplication
{
    get {
            if (this.InvokeRequired) 
            {
                return (ApplicationViewModel)this.Invoke(new Func<ApplicationViewModel>(() => this.SelectedApplication));
            }
            else
            { 
                return _applicationsCombobox.SelectedItem as ApplicationViewModel;
            }
        }
}

2 个答案:

答案 0 :(得分:2)

由于您使用的是.NET 2.0,因此您无法使用Func代理,但您可以使用MethodInvoker代理。

您无法在.NET 2.0中使用lambda表达式语法,但您可以使用&#34;匿名委托&#34;语法(这几乎是一样的),如下面的代码示例所示。

从非UI线程查询UI控件中的数据通常是不常见的事情;通常你的UI控件会触发在UI线程上执行的事件,因此你当时从UI控件中收集所需的数据,然后将这些数据传递给其他函数,这样你就不必担心这样做了一个调用。

但是,在你的情况下,你应该能够做到这样的事情:

public ApplicationViewModel SelectedApplication
{
    get
    {
        if (this.InvokeRequired)
        {
            ApplicationViewModel value = null; // compiler requires that we initialize this variable
            // the call to Invoke will block until the anonymous delegate has finished executing.
            this.Invoke((MethodInvoker)delegate
            {
                // anonymous delegate executing on UI thread due calling the Invoke method
                // assign the result to the value variable so that we can return it.
                value = _applicationsCombobox.SelectedItem as ApplicationViewModel;
            });
            return value;
        }
        else
        {
            return _applicationsCombobox.SelectedItem as ApplicationViewModel;
        }
    }
}

编辑:现在我看看你的.NET 4.0代码示例并查看Invoke函数,我看到它如何返回一个值(不是我之前有理由使用的东西)。< / p>

嗯,MethodInvoker委托不期望返回值,但正如@haiyyu指出的那样,您可以定义自己的委托。例如,您只需要定义自己的Func<TResult>委托,原始代码可能会正常工作:

// this is all that is required to declare your own Func<TResult> delegate.
delegate TResult Func<TResult>();

MSDN页面中的示例代码:

public partial class Form1 : Form
{
    public Form1()
    {
        // Create a timer that will call the ShowTime method every second.
        var timer = new System.Threading.Timer(ShowTime, null, 0, 1000);           
    }

    private void ShowTime(object x)
    {
        // Don't do anything if the form's handle hasn't been created 
        // or the form has been disposed.
        if (!this.IsHandleCreated && !this.IsDisposed) return;

        // Invoke an anonymous method on the thread of the form.
        this.Invoke((MethodInvoker) delegate
        {
            // Show the current time in the form's title bar.
            this.Text = DateTime.Now.ToLongTimeString();
        });
    }
}

答案 1 :(得分:1)

使用委托,它们是一种类型化的函数指针。 这里有更多阅读:http://msdn.microsoft.com/en-us/library/ms173171%28v=vs.80%29.aspx

相关问题