How do I change a value argument from within an event handler?

妖精的绣舞 提交于 2019-12-24 13:52:53

问题


I’m passing a bool to a method in another class by reference, so that I can change it (-the original argument) from within the method.

I also want an event (which is subscribed to by that method) to be able to change it.

Doing this:

class myCheckBox : CheckBox
{
    bool b1;
    public myCheckBox(ref bool b)
    {
        b1 = b;
        this.CheckedChanged += new EventHandler(myCheckBox_CheckedChanged);
    }

    void myCheckBox_CheckedChanged(object sender, EventArgs e)
    {
        b1 = Checked;
    }
}

doesn’t help, since b1 is only a copy of b.

Is there any way of doing: ref b1 = ref b; ? if not, how do I solve this?

(The examples are only to explain the question.)


回答1:


You'd typically pass an argument to your event handler that has a boolean property that can be modified by the event handler:

public class MyEventArgs : EventArgs
{
    public bool Value { get; set; }
}

public class MyClass
{
    public void method1(ref bool b)
    {
        MyEventArgs e = new MyEventArgs()
        {
            Value = b
        };
        eventMethod(e);

        b = e.Value;
    }

    void eventMethod(MyEventArgs e)
    {
        e.Value = false;
    }
}

You may also want to take a look at the standard event handler pattern established in .NET: How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide)




回答2:


Pass the class containing the field, a string denoting it, and save them instead of b1. Then use reflection.

See How to create a reference to a value-field




回答3:


Make b1 a public field of your class.

Or a private one, with a property with a public getter and a public setter.




回答4:


Well when I copied the code intyo a Console app (had to change to static functions and var b1 of course) it works as you want, when called from Main:

bool b = true;
method1(ref b);
Console.writeLine(b1);

prints 'false'....



来源:https://stackoverflow.com/questions/7923014/how-do-i-change-a-value-argument-from-within-an-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!