Fundamental .NET - How links are kept / resolved

Pay attention to the following code:

Control foo = null;
Control bar = null;
int i = 0;

protected void Page_Load(object sender, EventArgs e)
{
    test();
    test();
    Page.Controls.Add(foo);
}

void test()
{
    i++;
    bar = new Control();
    bar.Controls.Add(new LiteralControl(i.ToString()));
    if (foo == null)
    {
        foo = new Control();
        foo.Controls.Add(bar);
    }
}

When testing the above code, I was surprised to see that the result is printed: "1" (not "2").

I assume this is because when I add the control barto foo, it foo.Controls.Add()resolves the link bar, and not just saves the link.

1) Can someone confirm that this is so, or perhaps develop it?

2) I got a feeling that I am allowed to do foo.Controls.Add(ref bar);, it will show "2", but, obviously, this syntax is illegal. Is this possible without a lot of refactoring?

+3
5

Jon Skeet (), :

(, bar foo) , .

, test() , 1. foo.

test() , 2. foo.

? () bar = new Control(); . , foo Controls.

, , , :

Control foo = null;
Control bar = new Control();
int i = 0;

protected void Page_Load(object sender, EventArgs e)
{
    test();
    test();
    Page.Controls.Add(foo);
}

void test()
{
    i++;
    bar.Controls.Clear()
    bar.Controls.Add(new LiteralControl(i.ToString()));
    if (foo == null)
    {
        foo = new Control();
        foo.Controls.Add(bar);
    }
}

, , , , foo.

+3

foo.Controls.Add(bar);

bar. Control, a LiteralControl "1".

bar, ... , foo.Controls. bar Add, .

, , , , .. .NET, , . , ..

/ .

+6

. foo - . , test(), , . , (), LiteralControl "1". "1" - , i.

, foo.Controls.Add(ref bar) . () , . -, . .

bar, .

, , bar , test(), .

()

, :

 bar = new Control();

to

if (bar == null) bar = new Control();

, , "bar", , . (... acutally, "12", TWO LiteralControls).

+3

test() ( Control1) bar. foo null, , .

, Control1 bar, foo.Controls.

test() (Control2), a , . foo null, .

, bar Control2, foo.Controls Control1.

0

Well foo ( ), LiteralControl 1.

test() ( 1) . , , foo, .

0

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


All Articles