C# params 关键字和函数重载
在.net框架中,我经常看到如下重载函数,
public void Log(string message)
...public void Log(string message, params object[] args)
...
我的问题是,由于 params 关键字允许零个或多个参数,我们可以去掉第一个签名吗?只需第二个签名,我就可以像下面这样没有参数地调用它,所以我不知道为什么他们会有第一个签名?
Log("calling with no param");
In .net framework I constantly see overloaded functions like the following,
public void Log(string message)
...public void Log(string message, params object[] args)
...
my question is since the params keyword allows zero or more parameters, could we just get rid of the first signature? With just the second signature, I could call it with no parameters fine like below, so I don't know why they would have the first signature?
Log("calling with no param");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一个原因是 params 很慢,认为所有参数都收集完毕并构建了一个数组。所以第二个比较慢。
Another reason is
params
is slow, thinking that all parameters are collected and an array is built. So the second one is slower.如果无数组版本具有更简单的实现,通常会使用此模式。
This pattern is typically used if the array-less version has a simpler implementation.
还有一个小的速度优势。
调用一个非常简单的 (
count++
) 方法的 10 亿次迭代所花费的毫秒数:params
params
There is a small speed advantage as well.
Milliseconds taken for 1 billion iterations of calling a very simple (
count++
) method with each:params
params