Properly exposing a List?

前端 未结 8 1472
谎友^
谎友^ 2021-02-02 01:20

I know I shouldn\'t be exposing a List in a property, but I wonder what the proper way to do it is? For example, doing this:

public static          


        
8条回答
  •  臣服心动
    2021-02-02 01:28

    AsEnumerable and ReadOnlyCollection have problem when your enumeration is at midway and collection gets modified. These things are not thread safe. Returning them as an array and caching them at time of calling can be much better option.

    For example,

    public static String[] List{
       get{
          return _List.ToArray();
       }
    } 
    
    //While using ...
    
    String[] values = Class1.List;
    
    foreach(string v in values){
      ...
    }
    
    // instead of calling foreach(string v in Class1.List)
    // again and again, values in this context will not be
    // duplicated, however values are cached instance so 
    // immediate changes will not be available, but its
    // thread safe
    foreach(string v in values){
      ...
    }
    

提交回复
热议问题