Why use private members then use public properties to set them?

后端 未结 5 1538
故里飘歌
故里飘歌 2020-12-11 00:53

Seen a few examples of code where this happens:

public class Foo
{
    string[] m_workID;
    public string[] WorkID
    {
        get
        {
                     


        
5条回答
  •  生来不讨喜
    2020-12-11 01:14

    A property by itself doesn't provide anywhere to put the data - you need the field (m_workID) for storage, but it entirely correct to hide that behind a property for many, many reasons. In C# 3.0 you can reduce this to:

     public string[] WorkID {get; private set;}
    

    Which will do much of the same. Note that exposing an array itself may be problematic, as there is no mechanism for protecting data in an array - at least with an IList you could (if needed) add extra code to sanity check things, or could make it immutable. I'm not saying this needs fixing, but it is something to watch.

提交回复
热议问题