Best practice when returning an array of values (.NET)

后端 未结 8 912
灰色年华
灰色年华 2021-01-14 14:37

Usually my methods are as the following:

public List Method1(int input)
{
    var output = new List();
    //add some items to output
          


        
8条回答
  •  醉酒成梦
    2021-01-14 15:18

    "Framework Design Guidelines" (2nd ed) in §8.3.1 has quite a lot to say about collections as return values, summary:

    • DO NOT provide settable collection properties.
    • DO use Collection or a subclass of Collection for properties or return values representing read/write collections.
    • DO use ReadOnlyCollection, a subclass of ReadOnlyCollection, or in rare cases IEnumerable for properties or return values representing read-only collections.

    (and more, but these three capture the core).

    The first of those above: don't return reference to internal collection unless you want the user to be able to change it (and then likely you should have a custom type so you have a degree of control).

    I would return IList and ensure I do not define the actual type I am returning, unless I was returning an iterator (when I would use IEnumerable).

提交回复
热议问题