它是更好地从一个操作方法返回最具体的或最普通类型? [英] Is it better to return the most specific or most general type from an action method?

查看:234
本文介绍了它是更好地从一个操作方法返回最具体的或最普通类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是无论是利益或利弊?

What are the benefits or detriments of either?

推荐答案

我的指导方针一直是最具体的,最将军

My guidelines has always been most specific out, and most general in.

更一般的数据类型,使用它知道的数据类型越少,code。例如,如果一个方法返回集合,我将返回新创建的集合,该方法生产的。如果它返回一个内部数据结构,我会碰到它到的IEnumerable< T>

The more general your data type is, the less the code that uses it knows about the data type. For instance, if a method returns a collection, I would return the newly created collection that the method produced. If it returns an internal data structure, I would bump it up to IEnumerable<T>.

但是,如果它返回一个数组或列表&LT; T&GT; ,因为这是它在内部建,code,得到您的数据保持目前拥有获得更多的功能在您的收藏。

However, if it returns an array, or a List<T> because that's what it built internally, the code that gets hold of your data now has access to more functionality on your collection.

光谱的另一端,回归最一般的(范围内)的数据类型将意味着你总是返回的IEnumerable&LT; T&GT; 或所有集合相似,即使该方法建立了一个新的阵列内部和返回。调用code现在拥有集合的内容手动复制到一个新的数组或列表,如果这是调用code需要使用。

The other end of the spectrum, to return the most general (within limits) data type would mean that you always return IEnumerable<T> or similar for all collections, even if the method built a new array internally and returned that. The calling code now has to manually copy the contents of the collection into a new array or list, if that is what the calling code needs to use.

这意味着更多的,并且在大多数情况下,不必要的工作。

This means more, and in most cases, unnecessary work.

至于投入,我去的最普​​遍的类型,我可以使用,因此对于收藏,除非我特别需要一个数组,列表或类似的,我会接受的IEnumerable&LT; T&GT; 。通过这样做,我保证调用code少的工作要做。这可能意味着,我必须做一些内部的工作,所以这是一个折衷。

As for input, I go for the most general type I can use, so for collections, unless I specifically need an array or a list or similar, I will accept IEnumerable<T>. By doing so, I ensure that calling code has less work to do. This might mean that I have to do some work internally, so it's a trade-off.

最重要的部分是要达到一个平衡。不要太笼统或过于具体,所有的时间,每一次。找出正确的类型是有道理的,并考虑什么叫code是为了从code中传递数据或接受传出的数据做。工作越少越好。

The important part is to reach a balance. Don't be too general or too specific, all the time, every time. Figure out the right type that makes sense and consider what the calling code has to do in order to pass data in or accept outgoing data from your code. The less work, the better.

这篇关于它是更好地从一个操作方法返回最具体的或最普通类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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