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

时间:2014-09-30 05:30:01

标签: c# c#-4.0 c#-5.0

在传递数据的某些功能中,我看到了这样的语法

obj = new demo("http://www.ajsldf.com", useDefault: true);

这里的含义是什么?它与我们在方法中传递的其他参数有什么不同。

1 个答案:

答案 0 :(得分:10)

他们是Named Arguments。它们允许您为传入的函数参数提供一些上下文。

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

例如:这是错误的:

MyFunction(useDefault: true, other, args, here)

这很好:

MyFunction(other, args, here, useDefault: true)

MyFunction可能被定义为:

void MyFunction(string other1, string other2, string other3, bool useDefault)

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

MyFunction(
    other1: "Arg 1",
    other2: "Arg 2",
    other3: "Arg 3",
    useDefault: true
)

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

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

如果你看一下这个定义,那就有道理了:

public static Route MapRoute(
    this RouteCollection routes,
    string name,
    string url,
    Object defaults
)

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

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