c# - 为什么可以从属性访问私有(private) const 字段?

标签 c# oop attributes encapsulation private-members

这怎么可能?

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

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

这不违反封装原则吗?

最佳答案

不,这不违反封装。属性声明在逻辑上是类的一部分。 Attr 未访问 Test.E(它不能),您正在使用 E 调用 Attr 的构造函数> 来自 Test。这与初始化成员一样好。

C# 语法可能使它看起来像是属性以某种方式“位于”类之外,但事实并非如此。为此类生成的 IL 是这样的:

.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

如果 C# 采用类似的语法,它可能看起来像这样:

    class Test
    {
        attribute Attr(E);

        private const int E = 0;
    }

这会强调声明的范围,但可以说它不会那么清楚。当属性应用于成员时(在 IL 中,这些直接跟在声明之后),它变得更加不清楚。

关于c# - 为什么可以从属性访问私有(private) const 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44239087/

相关文章:

c++ - 在 C++ 中重载显式构造函数

c# - UIHint 无法解析抽象模型中的模板

c# - 可空引用类型和选项模式

c# - StackTrace/StackFrame 不返回生产环境中的预期信息

php - 开放库涵盖 API 速率限制

language-agnostic - 更喜欢组合而不是继承?

Python:如何确定属性(按名称)是类属性还是实例属性?

java - 部分访问类属性

python - 一个属性可以访问另一个属性吗?

c# - hangfire 重试如何在 recuringjob 中工作?