【问题标题】:Optional Parameter in C# 4.0C# 4.0 中的可选参数
【发布时间】:2012-10-08 09:14:52
【问题描述】:
 List<DynamicBusinessObject> dbo = SearchController.Instance.GetSearchResultList(search, null, "date", startRow - 1, ucDataPager1.PageSize, state);

上面的代码行调用 GetSearchResultList 方法,到目前为止该方法有 5 个参数。

我添加了第 6 个参数,但想让这个参数成为可选参数,这样调用这个函数的所有其他页面就不需要更新了。

所以我把函数改成这样:

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
    public List<DynamicBusinessObject> GetSearchResultList(Search search, List<CategoryAttribute> listCatAttrib, string sortBy, int startRow, int pageSize, [Optional, DefaultParameterValue("")] string state)
    {
        StorageQuery qry = new QrySearchResult(
            search.ID,
            (listCatAttrib != null && listCatAttrib.Count > 0) ? listCatAttrib[0].Attribute.ID : -1,
            (listCatAttrib != null && listCatAttrib.Count > 1) ? listCatAttrib[1].Attribute.ID : -1,
            (listCatAttrib != null && listCatAttrib.Count > 2) ? listCatAttrib[2].Attribute.ID : -1,
            1, sortBy, startRow, pageSize, state);
        List<DynamicBusinessObject> list = BusinessObject.Search(qry);
        return list;
    }

但是,当我尝试构建时,它给了我 GetSearchResultList 没有重载方法并且需要 5 个参数的错误。 我也尝试过使用 string state = "" 而不是使用 [Optional]

如果第 6 个参数是可选的,那么有人知道为什么它抱怨我在调用时没有传递 6 个参数吗?

【问题讨论】:

    标签: c#-4.0 optional-arguments


    【解决方案1】:

    你应该可以使用:

    ..., string state = "") {
    

    一个可能的问题是您的项目针对的是旧版本的 .NET。检查项目属性以确保它指向正确的版本。

    【讨论】:

    • 嗯,我在 web.config 中找到了编译器部分,它被设置为使用 3.5。我将其更改为 4.0 并在编译部分添加了 targetframework=4.0 ,这似乎已修复它。感谢您的建议。
    【解决方案2】:

    这些属性不是你在 c# 中定义可选参数的方式。

    相反,语法只是参数加上= &lt;value&gt;

    所以你的方法签名变成:

    public List<DynamicBusinessObject> GetSearchResultList(
        Search search, 
        List<CategoryAttribute> listCatAttrib, 
        string sortBy, 
        int startRow, 
        int pageSize,
        string state = "")
    

    虽然我建议使用 null 而不是空字符串,但如果这些签名被外部库使用,则默认类型更自然。

    可选参数就像常量,它们在编译时被烘焙到引用程序集中。

    假设您有另一个使用可选参数调用此方法的库,如下所示:

    myObj.GetSearchListResult(search, listCatAttrib, sortBy, startRow, pageSize);
    

    在你编译这个库的时候,调用实际上会写在你的库中:

    myObj.GetSearchListResult(search, listCatAttrib, sortBy, startRow, pageSize, "");
    

    然后,如果您将方法的声明更改为:

    public List<DynamicBusinessObject> GetSearchResultList(
        Search search, 
        List<CategoryAttribute> listCatAttrib, 
        string sortBy, 
        int startRow, 
        int pageSize,
        string state = "some value")
    

    第一个库中的调用将仍然传递一个空字符串,而不是新值。你必须重新编译你的方法的所有调用者以确保新值被接受。

    也就是说,这就是为什么如果你在你的程序集之外公开这个方法,你会使用重载而不是默认值;如果您更改了重载中传递给方法的值,您只需分发定义该方法的程序集,您不必分发并让所有针对该方法的调用者重新编译。

    【讨论】:

    • 感谢您的解释 - 原来我需要调整 web.config 以便它可以在 4.0 下运行。不过,我赞成你的回答。
    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 2011-04-26
    • 2011-03-19
    • 2011-10-28
    • 1970-01-01
    • 2011-04-06
    • 2011-07-24
    • 2011-10-03
    相关资源
    最近更新 更多