c# - 方法的数据类型是尽可能具体还是更通用更好?

标签 c# asp.net-mvc

在 ASP.Net MVC 中,如果我在 Controller 上有一个返回 View 的方法,该方法应该是 ViewResult 类型还是更通用的 ActionResult 类型?

最佳答案

ASP.NET 论坛上提出了类似的问题:http://forums.asp.net/t/1423519.aspx

基本上,这取决于风格——在 OOP 中,您尝试返回可以给定情况的最具体类型。你不回来object对于您拥有的每种方法 - 有时您会返回 string ,有时List ,有时是自定义类。

在论坛回复中,有人引用了 Stephen Walther 书中的内容:

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会是首选,特别是从单元测试的角度来看。

关于c# - 方法的数据类型是尽可能具体还是更通用更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3689530/

相关文章:

c# - 使用 Entity Framework 将更改保存到 SQL Server 数据库时,一个或多个实体的验证失败

asp.net-mvc - 使用 knockout 将枚举绑定(bind)到组合框

c# - 在 VS for mac 上运行项目

c# - 当内容高度可变时,列表框滚动条拇指改变大小

c# - 在基类中将 ToString 标记为虚拟,会发生什么?

asp.net-mvc - Visual Studio Online 网站以 Debug模式部署到 Azure

c# - 计算表中某列值的总和

c# - 使用 Try-Catch 处理看到的错误,不好吗?

c# - 检测表单已被 Dispose()ed 的正确方法

c# - 如何均匀展示banner?