Properly exposing a List?

前端 未结 8 1550
谎友^
谎友^ 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:45

    Exposing a List as a property isn't actually the root of all evil; especially if it allows expected usage such as foo.Items.Add(...).

    You could write a cast-safe alternative to AsEnumerable():

    public static IEnumerable AsSafeEnumerable(this IEnumerable data) {
        foreach(T item in data) yield return item;
    }
    

    But your biggest problem at the moment is thread safety. As a static member, you might have big problems here, especially if it is in something like ASP.NET. Even ReadOnlyCollection over an existing list would suffer from this:

            List ints = new List { 1, 2, 3 };
            var ro = ints.AsReadOnly();
            Console.WriteLine(ro.Count); // 3
            ints.Add(4);
            Console.WriteLine(ro.Count); // 4
    

    So simply wrapping with AsReadOnly is not enough to make your object thread-safe; it merely protects against the consumer adding data (but they could still be enumerating it while your other thread adds data, unless you synchronize or make copies).

提交回复
热议问题