📜  C#6.0 Default values for getter-only properties

📅  最后修改于: 2020-11-01 03:17:28             🧑  作者: Mango

C#设置只读属性的默认值

该特性允许我们为getter设置默认值。仅getter属性是只读属性。我们不能为该属性设置新值。编译器报告一个错误:不能在编译时分配,如果我们显式地分配值

C#Default values for getter-only properties示例1

using System;
namespace CSharpFeatures
{
    class Student
    {
        public string Name { get; } = "Rahul kumar";
        public string Email { get; } = "rahul@abc.com";
    }
    public class PropertyInitializer
    {
        public static void Main(string[] args)
        {
            Student student = new Student();
            Console.WriteLine(student.Name);
            Console.WriteLine(student.Email);
        }
    }
}

输出量

Rahul kumar
rahul@abc.com

让我们来看一个示例,如果我们显式分配值会发生什么。

C#Default values for getter-only properties示例2

using System;
namespace CSharpFeatures
{
    class Student
    {
        public string Name { get; } = "Rahul kumar";
        public string Email { get; } = "rahul@abc.com";
    }
    public class PropertyInitializer
    {
        public static void Main(string[] args)
        {
            Student student = new Student();
            Console.WriteLine(student.Name);
            Console.WriteLine(student.Email);
            student.Name = "john";
            Console.WriteLine(student.Name);
        }
    }
}

输出量

error CS0200: Property or indexer 'Student.Name' cannot be assigned to -- it is read only