它是最好能有一种方法的数据类型是尽可能具体,或更普遍? [英] Is it better to have a method's datatype be as specific as possible or more general?

查看:108
本文介绍了它是最好能有一种方法的数据类型是尽可能具体,或更普遍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.Net MVC的,如果我有一个返回视图应该是方法类型的ViewResult或更一般的ActionResult的控制器上的方法?

In ASP.Net MVC if I have a method on a controller that returns a View should that method be of type ViewResult or the more general ActionResult?

推荐答案

一个类似的问题被要求在ASP.NET论坛:的 http://forums.asp.net/t/1423519.aspx

A similar question was asked on the ASP.NET forums: http://forums.asp.net/t/1423519.aspx

基本上,它归结为风格 - 在OOP中,你试图返回,你能给出的情况下最具体类型。你不回对象为你拥有的每方法 - 有时你返回字符串,有时列表,有时一个自定义类。

Basically, it comes down to style -- in OOP, you try to return the most specific type that you can given the situation. You don't return object for every method that you have -- sometimes you return string, sometimes List, sometimes a custom class.

在论坛回帖,有人从他的书中引用斯蒂芬瓦尔特:

In the forum replies, someone quotes Stephen Walther from his book:

特别注意此操作方法
  声明它返回一个实例
  的的ViewResult。它会工作得的
  相同的,如果不是方法的返回类型
  是的ActionResult(基类
  所有行动的结果)。事实上,一些
  ASP.NET MVC的程序员声明所有
  他们的操作方法为返回
  非特异性的ActionResult,即使他们
  肯定知道它总会
  返回一个特定的子类。
  然而,这是一个行之有效的
  原则上面向对象
  编程的方法应该返回
  他们能最具体类型(如
  以及接受最一般的
  参数类型,他们可以)。以下
  这一原则最大化的便利
  和灵活性code调用
  你的方法,比如单元测试。

NOTE This action method specifically declares that it returns an instance of ViewResult. It would work just the same if instead the method return type was ActionResult (the base class for all action results). In fact, some ASP.NET MVC programmers declare all their action methods as returning a nonspecific ActionResult, even if they know for sure that it will always return one particular subclass. However, it's a well-established principle in object-oriented programming that methods should return the most specific type they can (as well as accepting the most general parameter types they can). Following this principle maximizes convenience and flexibility for code that calls your method, such as your unit tests.

因此​​,使用更具体的的ViewResult 将是preferred,特别是从单元测试的角度来看。

So using the more specific ViewResult would be preferred, especially from a unit testing perspective.

这篇关于它是最好能有一种方法的数据类型是尽可能具体,或更普遍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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