1
 List<DynamicBusinessObject> dbo = SearchController.Instance.GetSearchResultList(search, null, "date", startRow - 1, ucDataPager1.PageSize, state);

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

我添加了第 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 个参数?

4

2 回答 2

2

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

相反,语法只是参数 plus = <value>

所以你的方法签名变成:

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")

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

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

于 2012-10-18T01:26:01.820 回答
1

您应该能够使用:

..., string state = "") {

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

于 2012-10-18T01:23:28.877 回答