C # - why is it impossible to access 'this' in a field initializer?

Why does this lead to a compiler error:

class Foo
{
    public Bar Baz = new Bar(this);
}

But this is not so:

class Foo
{
    public Bar Baz;

    public Foo()
    {
        this.Baz = new Bar(this);
    }
}

Conceptually, the two are equivalent, aren't they?

+3
source share
6 answers

No, they are not completely equivalent ... the variable initializer is executed before any base class constructors are run. The constructor body is executed after the base class constructors are launched. (This is different from Java, where variable initializers are executed after the base class constructors, but before the constructor body.)

this : , ( ).

, , ...

+9

, . , , Bar , , .

+1

( ) . .

, - , , . . , , . , .

+1

, , .

+1
class Foo
{
    public Bar Baz = new Bar(this);
}

"this" "Foo". , .

, "Bar" "Foo", ( ), Bar ( "hello!" ), :

class Foo
{
    public static Bar Baz = new Bar("Hello!");
}

:

Foo.Baz.something();

, "" .

+1

, # vb.net. #, Foo: Bar: Boz: Object, :

  • Foo
  • Boz
  • Boz
  • Foo

vb.net :

  • Boz intializers
  • Boz
  • Foo
  • Foo

vb.net , , . , # , , , , , , ; , , , , ( , ).

, , vb.net, # , . vb, , , . , , MyArray[] , :

' ConstructorParam is defined and set in base class ParamInitClass(Of Integer)
  ReadOnly MyArray(ConstructorParam) As Integer
...
Sub New(ArraySize As Integer)
  MyBase.New(ArraySize)
End Sub

,

  ReadOnly MyArray() As Integer

Sub New(ArraySize As Integer)
  Redim MyArray(ArraySize)
End Sub

Note that in C # the only way to do such things is through variables threadstatic, but at best, such methods would be pretty dodgy.

0
source

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


All Articles