Do I need to use { get; set; } with c# fields that have no special actions when getting and setting

前端 未结 8 1242
借酒劲吻你
借酒劲吻你 2021-01-16 04:59

I have been coding classes like this:

public class ReportViewModel
    {
        public string Status;
        public string DataSource;
        public Stri         


        
相关标签:
8条回答
  • 2021-01-16 05:16

    They are different: your first two members are fields - not properties. The others are properties with auto-implemented accessors.

    0 讨论(0)
  • 2021-01-16 05:18

    { get; set; } indicate autoimplemented properties. In .NET there is a difference between properties and fields. Normally fields should be private. They are used for some specific implementation and should in most cases be internal to the class. Properties on the other hand are used to encapsulate behavior that is exposed to the consumers.

    0 讨论(0)
  • 2021-01-16 05:20

    At all depends on how this class will be used.

    If this is in your code, just used in your current product, then there isn't really much difference between fields (no {get;set;}) and properties (with the {get;set;}).

    However in that case they probably shouldn't be public, make them internal or private instead so that it's clear that external code shouldn't use them.

    If your class is going to be used by other assemblies then you should always convert public fields to properties.

    The reason is that if you want to extend properties later on (i.e. add a body to the set) then your users can just get the new DLL from you. However if you've used fields then converting them to a property will look the same in the IDE, but require your users to recompile when they get the altered DLL.

    Being public tells consumers that they can rely on that member being present, being a property gives you more control of how you deliver it to them.

    0 讨论(0)
  • 2021-01-16 05:29

    If you want them properly exposed as properties, yes.

    0 讨论(0)
  • 2021-01-16 05:37

    You've created a class with two public fields (Status and DataSource) and three public properties (DataStore, PageMeta and List). I would advise against having public fields - and you should actually consider whether you really need all of these to be mutable properties at all.

    There are various advantages to using properties over public fields, but the main one in my mind is that a property is logically part of the API of a class, whereas a field is logically an implementation detail. The property says what callers can do - a field says how a value is stored.

    0 讨论(0)
  • 2021-01-16 05:37

    When you don't add the get and set you are using a field rather than a property. Which in many cases won't make a lot of difference. However, you can't databind to a field like you can with a Property. So you would lose that.

    0 讨论(0)
提交回复
热议问题