代码之家  ›  专栏  ›  技术社区  ›  Shane Amare

构造函数和对象构造之间的区别是什么?

  •  0
  • Shane Amare  · 技术社区  · 2 年前

    我试图通过阅读 Microsoft Documentation .)在页面底部附近提到了三种修改“自动属性”的方法:

    • 使用 get; 只有
    • 使用 get; init;
    • 使用 get; private set;

    根据该文档,第一个实现用于使该属性在除构造函数之外的所有地方都是免疫的。第二个仅在对象构造期间是免疫的。第三个是当你希望房产对所有消费者都是免疫的。

    收到私有集; 很清楚这将在哪里实施,但我的问题是第一和第二种情况。使用构造函数和“对象构造”有什么区别?我认为它们是可交换的。但在这里,据我所知,这份文件暗示他们是不同的。我有什么东西不见了吗?还是我理解错误了?

    我试着在谷歌上搜索它,并在堆栈溢出中搜索。我看到很多帖子都在抨击类似的问题,强调两者之间的差异 收到 收到init; ,但我已经很清楚了。我找不到确切的问题答案。

    1 回复  |  直到 2 年前
        1
  •  3
  •   Enigmativity    2 年前

    对于差异的快速示例:

    class C
    {
        public int Prop1 { get; } = 2;
        public int Prop2 { get; init; } = 4;
    
        // constructor
        public C()
        {
            // Prop1 is only assignable here
            Prop1 = 6;
            // Prop2 is assignable here, but also in the "object initializer"
            Prop2 = 8;
        }
    }
    
    // the stuff inside the {} is what the docs are referring to
    // as "object initializer"
    var c = new C()
    {
        // this next line would be an error
        // Prop1 = 10,
    
        // setting Prop2 works fine,
        // this also overwrites what was set in the constructor 
        Prop2 = 10
    }
    

    Prop2 不能在这些{}结束后再次设置,这就是区别 init 从…起 set