简体   繁体   English

C#自动属性

[英]C# Automatic Properties

I'm a bit confused on the point of Automatic properties in C# eg 我对C#中的自动属性有点困惑,例如

public string Forename{ get; set; }

I get that you are saving code by not having to declare a private variable, but what's the point of a property when you are not using any get or set logic? 我知道你不需要声明私有变量来保存代码,但是当你不使用任何get或set逻辑时,属性的重点是什么? Why not just use 为什么不用

public string Forename; 

I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic? 我不确定这两个语句之间有什么区别,如果你想要额外的get / set逻辑,我一直认为你使用过属性?

Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface). 属性可以在不破坏合同的情况下放入代码,字段不能将代码放入其中而不将其更改为属性(并破坏接口)。 Properties can be read only or write only, fields can't. 属性可以是只读或只写,字段不能。 Properties can be data bound, fields can't. 属性可以是数据绑定,字段不能。

You can write 你可以写

public string Forename{ get; private set; }

to get read-only properties... Still not nearly as versatile as real properties, but it's a compromise that for some works. 获得只读属性......仍然没有真正的属性那么多功能,但它对某些作品来说是妥协。

I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic? 我不确定这两个语句之间有什么区别,如果你想要额外的get / set逻辑,我一直认为你使用过属性?

In the first case, the compiler will automatically add a field for you, and wrap the property. 在第一种情况下,编译器将自动为您添加一个字段,并包装该属性。 It's basically the equivalent to doing: 它基本上等同于:

private string forename;
public string Forename
{
    get
    { 
        return this.forename;
    }
    set
    {
        this.forename = value;
    }
}

There are many advantages to using properties over fields. 在字段上使用属性有许多优点。 Even if you don't need some of the specific reasons, such as databinding, this helps to future-proof your API. 即使您不需要某些特定原因(例如数据绑定),这也有助于为您的API提供面向未来的证明。

The main problem is that, if you make a field, but in v2 of your application, need a property, you'll break the API. 主要问题是,如果你创建一个字段,但是在应用程序的v2中,需要一个属性,你就会破坏API。 By using an automatic property up front, you have the potential to change your API at any time, with no worry about source or binary compatibility issues. 通过预先使用自动属性,您可以随时更改API,而无需担心源或二进制兼容性问题。

It is meant that you expect to add the logic later. 这意味着您希望稍后添加逻辑。

If you do so and have it as property from the beginning, you will not have to rebuild the dependent code. 如果您这样做并从头开始将其作为属性,则不必重建依赖代码。 If you change it from a variable to a property, then you will have to. 如果将其从变量更改为属性,则必须执行此操作。

Public data members are evil (in that the object doesn't control modification of it's own state - It becomes a global variable). 公共数据成员是邪恶的(因为对象不控制对其自身状态的修改 - 它成为全局变量)。 Breaks encapsulation - a tenet of OOP. 打破封装 - OOP的宗旨。

Automatic properties are there to provide encapsulation and avoid drudgery of writing boiler plate code for simple properties. 自动属性可以提供封装,避免编写简单属性的锅炉板代码的苦差事。

public string ID { get; set;}

You can change automatic properties to non-automatic properties in the future (eg you have some validation in a setter for example)... and not break existing clients. 您可以在将来将自动属性更改为非自动属性(例如,您在setter中进行了一些验证)...而不是破坏现有客户端。

string m_ID;
public string ID
{
   get { return m_ID; }
   set 
   { 
     //validate value conforms to a certain pattern via a regex match
     m_ID = value;
   }
}

You cannot do the same with public data attributes. 您不能对公共数据属性执行相同操作。 Changing a data attribute to a property will force existing clients to recompile before they can interact again. 将数据属性更改为属性将强制现有客户端重新编译,然后才能再次进行交互。

A property is like a contract, and you can change the implemenation of a property without affecting the clients using your classes and properties. 属性就像合同,您可以更改属性的实现,而不会影响使用类和属性的客户端。 You may not have any logic today, but as business requirements change and if you want to introduce any code, properties are your safest bet. 您今天可能没有任何逻辑,但随着业务需求的变化,如果您想引入任何代码,属性是您最安全的选择。 The following 2 links are excellent c# video tutorials. 以下2个链接是优秀的c#视频教程。 The first one explains the need of properties over just using fields and the second video explains different types of properties. 第一个解释了仅使用字段的属性需求,第二个视频解释了不同类型的属性。 I found them very useful. 我发现它们非常有用。

Need for the Properties in C# 需要C#中的属性

Poperties in C#, Read Only, Write Only, Read/Write, Auto Implemented C#中的特性,只读,只写,读/写,自动实现

For one, you can set the property to virtual and implement logic in an inheriting class. 例如,您可以将属性设置为虚拟并在继承类中实现逻辑。 You can also implement logic in the same class afterwards and there won't be side-effects on any code relying on the class. 您也可以在之后的同一个类中实现逻辑,并且不会对依赖于该类的任何代码产生副作用。

When adding auto properties the compiler will add get set logic into the application, this means that if you later add to this logic, and references to your property from external libraries will still work. 添加自动属性时,编译器会将get set逻辑添加到应用程序中,这意味着如果稍后添加到此逻辑,则从外部库对属性的引用仍然有效。

If you migrated from a public variable to a property, this would be a breaking change for other libraries that reference yours - hence, why not start with an auto property? 如果您从公共变量迁移到属性,这将是引用您的其他库的重大变化 - 因此,为什么不从一个自动属性开始? :) :)

Not all properties need get/set logic. 并非所有属性都需要获取/设置逻辑。 If they do, you use a private variable. 如果他们这样做,您使用私有变量。 For example, in a MV-something pattern, your model would not have much logic. 例如,在MV-something模式中,您的模型没有太多逻辑。 But you can mix and match as needed. 但你可以根据需要混合搭配。

If you were to use a field like you suggested in place of a property, you can't for example define an interface to describe your class correctly, since interfaces cannot contain data fields. 如果您要使用类似于建议的字段来代替属性,则不能定义正确描述类的接口,因为接口不能包含数据字段。

Take a look at the following code and explanation. 看一下下面的代码和解释。
The most common implementation for a property is getter or a setter that simply reads and writes to a private field of the same type as a property. An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates a private backing field.
Look into the following code:- 查看以下代码: -

    public class Stock 
    {
      decimal currentPrice ;  // private backing field.
      public decimal CurrentPrice 
      {
        get { return currentPrice ; }
        set { currentPrice = value ; }
      }
   }

The same code can be rewritten as :- 相同的代码可以改写为: -

   public class Stock
   {
     public decimal CurrentPrice { get ; set ; } // The compiler will auto generate a backing field.
   }

SOURCE:- C# in a Nutshell 消息来源: - C#in a Nutshell

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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