简体   繁体   English

有没有办法通过委托直接调用属性设置器?

[英]Is there a way to directly invoke a property setter through a delegate?

I am working with Windows Forms, and many times have bumped into (as I understood it) the necessity to write wrapping functions around properties of the UI components, so that they (the properties) could be set from another thread by invoking their wrappers. 我正在使用Windows窗体,并且很多时候已经碰到(据我所知)必须围绕UI组件的属性编写包装函数,以便可以通过调用它们的包装器从另一个线程设置它们(属性)。

However, one thing doesn't give me rest. 但是,有一件事并没有让我休息。 Are not the setters of properties actually functions themselves? 属性的设置者实际上不是自己运作的吗? If they are, could a Delegate be formed around them without resorting to writing wrappers, and then said delegate be invoked from another thread? 如果它们是,可以在它们周围形成一个委托而不求助于编写包装器,然后从另一个线程调用委托吗?

Yes, this is possible. 是的,这是可能的。 Use the PropertyInfo.GetSetMethod function to retrieve the set accessor for the property, and then create a delegate to invoke it. 使用PropertyInfo.GetSetMethod函数检索PropertyInfo.GetSetMethod的set访问器,然后创建一个委托来调用它。

Or even simpler yet, you could use the PropertyInfo.SetValue function to set the value directly. 或者甚至更简单,您可以使用PropertyInfo.SetValue函数直接设置值。

I can't find the real solution for this question but I figured it out. 我找不到这个问题的真正解决方案,但我明白了。 I sometimes need it myself but Google fails me. 我自己有时需要它,但谷歌让我失望。

Example: 例:

public string Blah
{
    get
    {
        if (InvokeRequired)
            return (string) Invoke(new Func<string>(() => Blah));
        else
            return Text;
    }
    set
    {
        if (InvokeRequired)
            Invoke(new Action(() => { Blah = value; }));
        else
            Text = value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM