最佳实践返回值的数组时(.NET) [英] Best practice when returning an array of values (.NET)

查看:142
本文介绍了最佳实践返回值的数组时(.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我的方法主要有以下几点:

 公开名单< INT>方法一(INT输入)
{
    无功输出=新的名单,其中,INT>();
    //添加一些项目输出
    返回输出;
}
 

但建议的FxCop另一IList实现的,而不是名单,但我不记得哪。该方案包括返回它作为一个IList,ICollection的或IEnumerable的更多的灵活性,或者一个完全不同的方式为code以下:

 公众诠释[]方法2(INT输入)
{
    无功输出=新的名单,其中,INT>();
    //添加一些项目输出
    返回output.ToArray();
}
 

所有的选择,都提供了和所有的可能性,这被认为是最好的做法呢?

解决方案

框架设计指南(第二版)在§8.3.1有相当大谈收藏的返回值,总结:

  • 不要提供可设置的集合属性。
  • DO 使用收藏< T> 或子类收藏< T> 对属性或返回值重新presenting读/写集合。
  • DO 使用 ReadOnlyCollection还< T> ,的一个子类 ReadOnlyCollection还< T> ,或在极少数情况下的IEnumerable< T> 的属性或返回值重新presenting只读集合。

(多,但是这三个捕获核心)。

其中第一个上面:不,除非你希望用户能够改变它(然后可能你应该有一个自定义的类型,所以你有一定程度的控制)返回引用内部集合。

我会回来的IList< T> ,并确保我没有定义的实际类型我回来,除非我是返回一个迭代器(当我将使用的IEnumerable< T>

Usually my methods are as the following:

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

But FxCop advises another IList implementation instead of List, but I can't remember which. The alternatives include returning it as an IList, ICollection or IEnumerable for more flexibility or a whole different way as the code below.:

public int[] Method2(int input)
{
    var output = new List<int>();
    //add some items to output
    return output.ToArray();
}

Of all alternatives, all provided and all possibilities, which is considered the best practice?

解决方案

"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<T> or a subclass of Collection<T> for properties or return values representing read/write collections.
  • DO use ReadOnlyCollection<T>, a subclass of ReadOnlyCollection<T>, or in rare cases IEnumerable<T> 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<T> and ensure I do not define the actual type I am returning, unless I was returning an iterator (when I would use IEnumerable<T>).

这篇关于最佳实践返回值的数组时(.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆