1. Naming and optional parameters
Visual C # 2010 introduces naming and optional parameters, and developers who often use SQL Server to write stored procedures should be familiar with this-named and optional parameters are very similar to stored procedure parameters.
A named parameter allows the caller to assign a value to the parameter by supplying its name, so the position of the parameter is not important. Optional parameters allow you to assign values to certain parameters when you define them, and you can ignore these "optional" arguments when invoked. Named and optional parameters can be applied to methods, indexers, constructors, and delegates. Named parameters and optional parameters are combined with dynamic types to facilitate access to COM APIs such as the Office Automation API.
1.1 Named parameters
The syntax for named arguments is:
参数名称1:参数值1,参数名称2:参数值2…
For example, the following code:
static void Main(string[] args)
{
CreateUser (password:"adminpassword",name:"admin");
}
static void CreateUser(string name, string password)
{
Console.WriteLine("name:{0},password:{1}", name, password);
}
You can see that the position of the parameter is not important because the named argument is used at the time of the call.
1.2. Optional Parameters
The definitions of methods, constructors, indexers, and delegates can specify whether their arguments are required or optional, and must provide the required arguments when invoked, but optional arguments can be omitted.
You can also use the System.Runtime.InteropServices.OptionalAttribute attribute class to define optional parameters that have been included in the base class library since the age of 1.0.
The definition of each optional parameter contains the default value (the default value must be a constant), and if it is not specified at the time of the call, the default value is used. For example, the following code:
static void Main(string[] args)
{
CreateUser ("admin","adminpassword",50);
}
/// <summary>
/// 创建用户
/// </summary>
/// <param name="name">用户名称</param>
/// <param name="password">用户密码</param>
/// <param name="score">积分 </param>
/// <param name="isLocked">是否锁定</param>
static void CreateUser(string name, string password,
int score=20,bool isLocked=false)
{
Console.WriteLine("name:{0},password:{1}", name, password);
}