how to return a value from main form to a differnt form or class(C#)

前端 未结 3 1009
慢半拍i
慢半拍i 2021-01-22 02:38

For some unknown reasons this silly thing cant be implemented.

I have an int count in the main form which I want to return to another class or form.

<
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 03:19

    This code will create a new instance of your Login form. Each instance will have its own instance variable count.

    login obj = new login();
    MessageBox.Show(obj.namecount().ToString());
    

    The default value for an integer is 0, so each time you create a new instance of the form it will have the value of 0 in the count variable. If you want to have all instances of the form have the same value for count, you should make count static.

    private static int count;
    

    When the variable is static, there will be only one instance of count shared by all instances of the Login form.

    var form1 = new login();
    // mouse up event fires on form1, value of count is set to 3 (for example)
    var form2 = new login();
    form2.namecount(); // returns 3
    

    Depending on what you want to do, there are other patterns, like using events, or a mediator that can help pass messages between components. This way when something happens in one form, other forms can react to the change without actually needing to reference or even know about the other forms in the application.

提交回复
热议问题