简体   繁体   中英

Read-Only Property in C# 6.0

Microsoft introduce a new syntax in C#6 that let you set your property to read-only as below:

public class Animal
{
    public string MostDangerous { get; } = "Mosquito";
}

I am wondering what is the added value of such approach.

What is the difference by just writing:

public class Animal
{
    public const string MostDangerous = "Mosquito";
}

or even:

public class Animal
{
    public string MostDangerous 
    { 
        get
        {
            return "Mosquito";
        }
    }
}

Your example is using string constants which can't show all the possibilities. Look at this snippet:

class Foo
{
    public DateTime Created { get; } = DateTime.Now;  // construction timestamp

    public int X { get; } 

    public Foo(int n)
    {
        X = n;  // writeable in constructor only
    }
}

Read only properties are per-instance and can be set from the constructor. Very different from a const field whose value must be determined at compile time. The property initializer is a separate feature and follows the rules and limitations of field initializers.

The newer syntax is an effort in reducing the verbosity of C#. It's just syntactic sugar. The IL generated is similar to an auto property with a getter and a backing store.

这种对 C# 的改进直接来自 VB,并且不需要实现支持字段和构造函数初始值设定项:

Public ReadOnly dateStamp As DateTime = Datetime.Now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM