Are nested types implicitly static?

The C # 5.0 language specification says:

Note that constants and nested types are classified as static members.

so if i write:

class A
{
   int a;

   class B
   {
       public void foo()
       {
           int j = a; // ERROR
       } 
   }
}

assignment a to j gives me error CS0120

"An object reference is required for a non-static field, method or 'member' property ''

therefore, I realized that it foois also implicit static.

However, when I look at both the decompiled code and the IL code, there is no pointer to a static keyword!

internal class A
{
    private class B
    {
        public void foo()
        {
        }
    }

    private int a;
}


// Nested Types
    .class nested private auto ansi beforefieldinit B
        extends [mscorlib]System.Object
    {
        // Methods
        .method public hidebysig 
            instance void foo () cil managed 
        {

        } 
        ...
    }

Is a nested type a truly static type with all implicitly static methods?

+4
source share
2 answers

" "

?

- , .

, .

, .

,

public class Parent
{
    public class Child
    {
    }
}

new Parent.Child(), new Parent() - .


, - ,

class A
{
   int a;

   class B
   {
       public void foo()
       {
           int j = a; // ERROR
       } 
   }
}

, A.B.foo() a ( ) a, B a .


, ,

public class Parent
{
    private int field;

    public class Child
    {
        public void WriteFieldFromParent(Parent parent)
        {
            Console.WriteLine(parent.field);
        }
    }
}

! field Parent Parent.Child, . , Parent Parent.Child.WriteFieldFromParent.

, MSDN ( , ) , , :

, . , .

+14

, a . - :

class A
{
   int a;

   class B
   {
       public void foo()
       {
           int j = new A().a;
       } 
   }
}

class A
{
    static int a;

    class B
    {
        public void foo() {
            int j = a;
        }
    }
}
0

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


All Articles