C# Automatic Properties

天涯浪子 提交于 2019-12-17 15:38:14

问题


I'm a bit confused on the point of Automatic properties in C# e.g

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? 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?


回答1:


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.




回答2:


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.




回答3:


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?

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.

The main problem is that, if you make a field, but in v2 of your application, need a property, you'll break the 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.




回答4:


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.




回答5:


Consider looking at some related threads about Difference Between Automatic Properties and Public Fields, Fields vs Properties, Automatic Properties - Useful or Not?, Why Not to Use Public Fields.




回答6:


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.

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 (e.g. you have some validation in a setter for example)... and not break existing clients.

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.




回答7:


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.




回答8:


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.

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? :)




回答9:


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. 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.




回答10:


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. 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#

Poperties in C#, Read Only, Write Only, Read/Write, Auto Implemented




回答11:


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



来源:https://stackoverflow.com/questions/1294660/c-sharp-automatic-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!