在 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/