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

6
在一些函数中,当传递数据时,我看到了这样的语法。
obj = new demo("http://www.ajsldf.com", useDefault: true);

这里的:是什么意思,与我们传递给方法的其他参数有何不同?
1个回答

11

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

它们必须在调用函数时放在所有非命名参数之后,如果有多个,可以按任何顺序传递,只要它们在任何非命名参数之后即可。

例如,这是错误的:

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路由,很难明白下面这段代码在做什么:

This can be really nice when you need to provide some context in an otherwise hard to comprehend function call. Take MVC routing for example, its hard to tell what's happening here:


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 }
);

2
此外,如果有多个命名参数,我们可以以任何顺序传递它们。 - Pankaj
1
感谢MSDN的参考,我明白了我想知道的内容。命名参数使您无需记住或查找调用方法参数列表中参数顺序的需要,我可以按任何顺序调用我的参数是主要优点。时间限制结束时将接受您的答案。 - Mohit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接