Why can I access a private constant from an attribute?

How is this possible?

namespace test
    {
        class Attr:Attribute
        {
            public Attr(int e)
            {
            }
        }

        [Attr(E)]
        class Test
        {
            private const int E = 0;
        }
    }

Does encapsulation principle violate?

+6
source share
1 answer

No, this does not break encapsulation. An attribute declaration is logically part of the class. Attrdoes not have access to Test.E(it cannot), you call the constructor Attrwith Efrom Test. This is as good as if you initialized the member.

C # syntax may look as if the attribute is “outside” the class in some way, but it is not. The IL produced for this class is as follows:

.class private auto ansi beforefieldinit test.Test
    extends [mscorlib]System.Object
{
    .custom instance void test.Attr::.ctor(int32) = (
        01 00 00 00 00 00 00 00
    )
    // Fields
    .field private static literal int32 E = int32(0)

    ...

} // end of class test.Test

# , :

    class Test
    {
        attribute Attr(E);

        private const int E = 0;
    }

, , , . , ( IL, ).

+3

All Articles