何时使用 params 作为方法参数的真实示例是什么?
据我了解, params 只是语法糖,“在幕后”只是为您提供了您指定类型的数组。
首先,你什么时候会使用这个?
其次,为什么要使用它而不是仅仅声明一个数组参数?
As I understand it, params
is just syntactic sugar that "under the hood" simply gives you an array of the type you specify.
First, when would you use this?
Second, why would you use it instead of just declaring an array argument?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Math.Min 仅接受两个参数。这是一个愚蠢的限制。许多其他语言允许您编写:
如果您想编写一个可以像这样使用的
min
函数,您需要使用params
。Math.Min
takes exactly two arguments. This is a stupid limitation. Many other languages allow you to write:If you wanted to write a
min
function that could be used like that, you'd want to useparams
.一个明显的例子可以在像
String.Format()
这样的方法中找到。使用 params 的这条语句很容易理解:但是如果没有 params,那就有点困难了:
我发现自己在像这样的字符串函数中使用了很多 params。我使用它只是为了提高代码的可读性。
An obvious example can be found in a method like
String.Format()
. This statement using params is easy to follow:But without params it's a bit more difficult:
I find myself using params alot for string functions like these. I use it just to improve the readability of the code.
我使用它的一种方法是将 sql 查询传递给我的包装类。我将有一些带有可变数量参数的sql。这样我就可以列出我随查询发送的所有参数,而不是先创建一个数组。
比替代方案好得多:
SQLWr
当您遇到需要可变数量参数的情况时,使用它会很好。
One way that I used it is in passing sql queries off to my wrapper class. I'll have some sql with a variable number of parameters in it. This way I can just list all of the parameters I'm sending with the query rather than creating an array first.
Much nicer than the alternative:
SQLWr
Its nice to have when you run into a situation where you need a variable number of arguments.
基类库中的一个示例是
String.Split(params char[]separator)
,允许您编写,例如:而不是
An example from the Base Class library is
String.Split(params char[] separator)
, allowing you to write, for example:rather than
我发现自己使用参数的主要不漂亮/更容易理解的原因是执行存储过程。
以数据库中有数百个存储过程的情况为例。那么你实际上只有两个选择
1:为每个存储过程单独编写代码,这将需要几个月的时间
2:创建一个通用执行器方法,它将运行任何存储过程并接受任何数字和参数。参数类型例如
The main non-prettier / easier to understand reason I find myself using params is in executing stored procedures.
Take the case where you have several hundred stored procedures in a database. Then you really only have two choices
1: Write code individually for each stored procedure which would take months
2: Create a generic executor method which will run any stored procedure and take any number & type of parameters e.g.