【问题标题】:Colon Parameters in C#, What does the colon stands for [duplicate]C#中的冒号参数,冒号代表什么[重复]
【发布时间】:2014-11-24 15:24:16
【问题描述】:

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

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

这里的是什么意思:和我们在方法中传递的其他参数有什么不同。

【问题讨论】:

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


    【解决方案1】:

    他们是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 }
    );
    

    【讨论】:

    • 另外,如果有多个命名参数,我们可以按任意顺序传递它们
    • 感谢 MSDN 参考我知道了我想知道命名参数使您无需记住或在调用方法的参数列表中查找参数的顺序,我可以调用我的参数以任何顺序都是主要的好处。时限结束后将接受您的回答
    猜你喜欢
    • 2011-08-21
    • 2019-09-14
    • 1970-01-01
    • 2014-02-05
    • 2019-07-24
    • 2012-09-25
    • 2014-12-18
    • 1970-01-01
    相关资源
    最近更新 更多