.NET(C#)中,自动属性(Auto-Implemented Properties)提供了一种简洁的方式来实现属性而无需显式定义字段。但直到C# 6.0版本之前,不能在自动属性的声明中直接为其指定默认值。从C# 6.0开始,可以在自动属性声明中直接初始化默认值。

1、在构造函数中设置默认值

在C#的早期版本中,或者当需要更复杂的初始化逻辑时,可以在类的构造函数中设置自动属性的默认值。如自动属性是静态的(即属于类本身而不是类的实例),则可以在静态构造函数中设置其默认值。

1)在构造函数中设置默认值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication
{
    class Person 
    {
        public Person()
        {
            Name = "Default Name";
        }
        public string Name { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            Console.WriteLine(p.Name);
            Console.ReadKey();
        }
    }
}

2)使用一般写法设置默认值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication
{
    class Person 
    {
       private string name = "Default Name";
       public string Name 
       {
           get 
           {
               return name;
           }
           set
           {
               name = value;
           }
       }
    }
  
    public class MyClass
    {
        public static int MyStaticProperty { get; set; }
    
        static MyClass()
        {
            MyStaticProperty = 10; // 在静态构造函数中设置默认值
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            Console.WriteLine(p.Name);
            Console.WriteLine(MyClass.MyStaticProperty);
        }
    }
}

2、 直接在自动属性中初始化(C# 6.0及以后)

从C# 6.0开始,可以在自动属性的声明中直接指定默认值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication
{
    class Person 
    {
       public string Name { get; set; } = "Default Name";

    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            Console.WriteLine(p.Name);
        }
    }
}

3、使用属性初始化器(C# 9.0及以后)

从C# 9.0开始,可以使用属性初始化器(Property Initializers)在创建对象时直接初始化属性。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication
{
    class Person 
    {
       public string Name { get; set; } = "Default Name";

    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person() { Name = "cjavapy.com" };
            Console.WriteLine(p.Name);
        }
    }
}

推荐文档