可选参数的条件使用

时间:2014-06-09 20:20:16

标签: c#-4.0 boolean .net-4.5 optional-parameters

我有课程:

public class Result{
    public string Name {get; set;}
    public string Category {get; set;}
    }

public SearchResults {
    public string PageNum {get; set;}
    public string PageSize {get; set;}
    public string TotalCount {get; set;}
    public IEnumerable<Result> Results {get; set;)
    }

我有方法:

public SearchResults GetSearchResults(bool full = false)
{
    return new SearchResults {
       PageNum = 1,
       PageSize = 25,
       TotalCount = 100,
       Results = new[] {new Result {Name="Alpha", Category="Bravo"}}
      // return Results only if parameter [full] is true ???How
    };
}   

在上面的方法中,我只想在[full]参数为true时返回[Results]。并且默认情况下不会返回它。

1 个答案:

答案 0 :(得分:1)

您可以使用Conditional operator并返回null作为结果:

Results = full ? new[] { new Result { Name = "Alpha", Category = "Bravo" } } : null,

默认情况下,Result是一个属性,它将被分配null (默认)

所以你的方法就像:

public SearchResults GetSearchResults(bool full = false)
{
    return new SearchResults
    {
        PageNum = 1,
        PageSize = 25,
        TotalCount = 100,
        Results = full ? new[] { new Result { Name = "Alpha", Category = "Bravo" } } : null,
    };
}