Is read-only auto-implemented property possible?

后端 未结 7 1608
你的背包
你的背包 2020-12-15 02:34

I found a topic on MSDN that talks that yes, this is possible.

I did a test that seems to break this statement:

using System;

namespace Test
{
    c         


        
7条回答
  •  旧巷少年郎
    2020-12-15 03:05

    The answer below was written back in 2010. In C# 6 (released in 2015) you can write read-only automatically-implemented properties:

    // This can only be assigned to in a constructor
    public int Foo { get; }
    

    You're absolutely right. Properly read-only automatically implemented properties are currently impossible. Making the setter private isn't the same thing, regardless of what some books and MSDN might say :)

    If I ruled the world, this would not be the case. When I see some of the language designers at NDC 2010 in June (please come along!) I intend to try to persuade, bribe, cajole and generally make a nuisance of myself until they agree. It's just one wafer-thin feature, after all.

    Looking at that MSDN article, the text itself doesn't say that it creates a read-only automatic property. It creates an immutable type using an automatic property, and that's correct. The only problematic bits are the comments saying

    // Read-only properties.
    

    ... which are definitely wrong. The framework agrees with us:

    var prop = typeof(Contact).GetProperty("Name");
    Console.WriteLine(prop.CanWrite); // Prints True
    

提交回复
热议问题