Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 518
Srv19 Avatar asked May 16 '11 11:05

Srv19


2 Answers

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.

Or even simpler yet, you could use the PropertyInfo.SetValue function to set the value directly.

like image 127
Cody Gray Avatar answered Sep 28 '22 06:09

Cody Gray


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;
    }
}
like image 44
Bitterblue Avatar answered Sep 28 '22 06:09

Bitterblue