Skip a parameter by reference between two forms

I have two forms (Form1 and Form2). In Form1, there is a variable public public i, which is set to 1 in the constructor of Form1. Then I open Form2 from Form1 with this code:

Form2 f2 = new Form2(ref i);
f2.ShowDialog();

The constructor of form 2 looks like this:

public int i;
public Form2(ref int x)
{
    InitializeComponent();
    i = x;
}

Then I set the variable I in Form2 to 2 and close Form2. Now I would expect the variable I in Form1 to have a value of 2 (due to the ref keyword, passing parameters), but the value is still 1. What am I doing wrong and why does the ref keyword not work in my example?

thanks

+3
source share
8 answers

What is really going on.

  • You create an object1 with an integer member named "i"
  • "i" . "i" "x".
  • "x" , "i".
  • object2. object1.i.
  • object2.i( object1.i, , ). object1.i .

, , , , 1 2.

Class Form1
{
    Object i = new Object();
    ...
    public void DoSomething()
    {
        Form2 f = new Form2(i);
        f.Show();
    }
}

, , , .

+6

"ref" . ... .

:

i = x;

. i x .

: / ( ), ref .

, : (Form2. i ) .

+6

Form1 Form2, . (.. , Form1 Form2)

- :

public partial class Form1 : Form
{
    public delegate void FormReturn(string s);
    private string var1;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var frm = new Form2(ReturnFunc);
        frm.ShowDialog();
    }

    protected void ReturnFunc(string text)
    {
        var1 = text;
    }
}

public partial class Form2 : Form
{
    private Form1.FormReturn returnFunc;

    public Form2(Form1.FormReturn del)
    {
        InitializeComponent();
        returnFunc = del;
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        returnFunc.Invoke(txtText.Text);
        Close();
    }
}
, . form1.
+2

, , , , , .

class Form1 {  
  public int i;
  public void doSomething(){
    Form2 f = new Form2(&i);
    f.showDialog();
  }
}

Form2 .

class Form2 {
  public int *i;
  public Form2(int *r){
    InitializeComponent();
    i = r;
  }
  public void setI(int v){
    *i = v;
  }
  public int getI(){
    return *i;
  }
}

, .

+1
i = x;

x. x, . .

x=2;
0

ref keyword : Form2. , form1 form2 ( , ValueType)

0

, , , . .

0

...

Form2 Form1:

  • ,
  • Form1 'private int myVariable' 'public int MyVariable' get set. Form1 Form2, Form1.MyVariable

? ? ( Form1 Form2)

0
source

Source: https://habr.com/ru/post/1718184/


All Articles