编程之路转自:cjavapy.com/article/55/
_ .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);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?