[英]Why in this C# .NET controller method do I have this signature?
I am pretty new to C# .NET and I have the following doubt. 我对C#.NET还是很陌生,但我有以下疑问。
On a page on which I am working on I found the following link: 在我正在处理的页面上,我找到了以下链接:
<a class="ui-btn-inline ui-btn ui-icon-delete ui-btn-icon-notext ui-corner-all" href="@Url.Action("Delete", "Groups", new { id = item.gruppoId })">Delete</a>
This link call a Delete() method on a GroupsController class. 此链接在GroupsController类上调用Delete()方法。
Ok, this is this method: 好的,这是这种方法:
public ActionResult Delete(int id = 0)
{
.......................
.......................
.......................
DO SOME STUFF
.......................
.......................
.......................
return View(model);
}
My doubt is related to the signature of this method: why is the parameter int id = 0 ? 我的疑问与该方法的签名有关:为什么参数int id = 0 ?
What does the = 0 mean? = 0是什么意思? To begin with I thought that this was a simple initialization and that it change the it value to 0 but using the debbugger I discovered that it don't change the id value.
首先,我认为这是一个简单的初始化,它将it值更改为0,但是使用调试器后,我发现它不会更改id值。 So what it exactly do?
那到底是怎么做的呢?
It's called an optional parameter. 它称为可选参数。 It means you can call the method with no argument, like this:
这意味着您可以不带参数地调用方法,如下所示:
Delete();
If you do that, the value of the id
parameter in the function will be 0
. 如果这样做,函数中
id
参数的值将为0
。
You're right in saying that the = 0
sets the value of the id
parameter. 您说对了
= 0
设置id
参数的值。
But it's important to note that it only does so when you do not pass that parameter . 但是要注意,只有在不传递该参数的情况下才这样做 ,这一点很重要。
Take for example: 举个例子:
public void SaySomething( var something = "Hello" )
{
Console.WriteLine( something );
}
//...
SaySomething();
SaySomething("I am sleeping.");
The first call to the function does not pass a parameter. 对该函数的第一次调用未传递参数。 Therefore, the default value
"Hello"
is used to write to the console. 因此,默认值
"Hello"
用于写入控制台。
The second call already sets a value for the parameter, so it does not get overwritten by the default value you set up. 第二个调用已经为参数设置了一个值,因此不会被您设置的默认值覆盖。
"I am sleeping."
will be printed in this case. 在这种情况下将被打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.