C#中的冒号参数,冒号代表什么

Moh*_*hit 5 c# c#-5.0 c#-4.0

在传递数据的某些函数中,我看到过这样的语法

obj = new demo("http://www.ajsldf.com", useDefault: true);
Run Code Online (Sandbox Code Playgroud)

这是什么意思:这里以及它与我们在方法中传递的其他参数有何不同.

Sim*_*ead 10

它们是命名参数.它们允许您为传入的函数参数提供一些上下文.

在调用函数时,它们必须是最后一个..在所有非命名参数之后.如果有多个,它们可以按任何顺序传递..只要它们来自任何未命名的.

例如:这是错误的:

MyFunction(useDefault: true, other, args, here)
Run Code Online (Sandbox Code Playgroud)

这可以:

MyFunction(other, args, here, useDefault: true)
Run Code Online (Sandbox Code Playgroud)

MyFunction可能被定义为:

void MyFunction(string other1, string other2, string other3, bool useDefault)
Run Code Online (Sandbox Code Playgroud)

这意味着,您也可以这样做:

MyFunction(
    other1: "Arg 1",
    other2: "Arg 2",
    other3: "Arg 3",
    useDefault: true
)
Run Code Online (Sandbox Code Playgroud)

当你需要在难以理解的函数调用中提供一些上下文时,这可能非常好.以MVC路由为例,很难说出这里发生了什么:

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
Run Code Online (Sandbox Code Playgroud)

如果你看一下定义..它是有道理的:

public static Route MapRoute(
    this RouteCollection routes,
    string name,
    string url,
    Object defaults
)
Run Code Online (Sandbox Code Playgroud)

然而,使用命名参数,在不查看文档的情况下更容易理解:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

  • 另外,如果有多个命名参数,我们可以按任意顺序传递它们 (2认同)