C# 中的自动实现属性
介绍
在 C# 3 版发布之前,使用面向对象编程范式的程序员面临一个很大的难题。该范式如下:属性应该是私有和公共字段的get-set映射。此附加层按指导原则使用。大多数人抵制了简单地声明公共字段并使用它们的冲动。
在本指南中,我们将了解自动实现的属性,这是 C# 版本 3 中引入的一项新功能,并了解它如何改善许多开发人员的生活。
自动属性
在以下示例中,我们将首先声明一个简单的类。此类表示一个具有名称、位置和序列号的网络设备。
using System;
namespace Pluralsight
{
public class NetworkDevice
{
private string name;
private string location;
private string serial;
public string Name
{
get { return name; }
set { name = value; }
}
public string Location
{
get { return location; }
set { location = value; }
}
public string Serial
{
get { return serial; }
set { serial = value; }
}
public static void Main()
{
NetworkDevice sw = new NetworkDevice();
sw.Name = "L2 switch";
sw.Location = "Amsterdam";
sw.Serial = "S1212323";
Console.WriteLine($"The device's name is {sw.Name}, the location is {sw.Location}, the serial is {sw.Serial}");
Console.ReadKey();
}
}
}
执行代码得到以下结果。
The device's name is L2 switch, the location is Amsterdam, the serial is S1212323
代码演示了在自动实现属性之前实现是如何工作的,这是面向对象编程所推荐的。代码被额外的层稍微混淆了一点,该层是公共属性和私有属性之间的映射。从 C# 版本 3 开始,这种困境不再存在。我们可以跳过 private 行,我们也不需要get-set的定义。
这样,我们的代码就变得更干净了。
using System;
namespace Pluralsight
{
public class NetworkDevice
{
public string Name { get; set; }
public string Location { get; set; }
public string Serial { get; set; }
public static void Main()
{
NetworkDevice sw = new NetworkDevice();
sw.Name = "L2 switch";
sw.Location = "Amsterdam";
sw.Serial = "S1212323";
Console.WriteLine($"The device's name is {sw.Name}, the location is {sw.Location}, the serial is {sw.Serial}");
Console.ReadKey();
}
}
}
输出是一样的。
结论
总而言之,引入这一新功能有助于人们重新组织代码。结果是易于维护且易于理解的代码。现在我们不需要使用字段声明或任何代码来让get-set方法修改字段。这由编译器自动处理。在幕后,编译器创建私有字段并确保映射,它还填充get-set方法以允许读取和写入特定字段。
我希望本指南对您有所帮助,并感谢您阅读它!
免责声明:本内容来源于第三方作者授权、网友推荐或互联网整理,旨在为广大用户提供学习与参考之用。所有文本和图片版权归原创网站或作者本人所有,其观点并不代表本站立场。如有任何版权侵犯或转载不当之情况,请与我们取得联系,我们将尽快进行相关处理与修改。感谢您的理解与支持!
请先 登录后发表评论 ~