问题描述:

This question already has an answer here:

  • C# method call with parameter name and colon

    6 answers

网友答案:

They are Named Arguments. They allow you to provide some context to the function argument you are passing in.

They must be last .. after all non-named arguments when calling a function. If there is more than one, they can be passed in any order.. as long as they come after any non-named ones.

E.g: this is wrong:

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

This is fine:

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

Where MyFunction might be defined as:

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

This means, you can also do this:

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

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

If you look at the definition .. it makes sense:

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

Whereas, with named arguments, its much easier to comprehend without looking at the documentation:

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