我有课程:
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]。并且默认情况下不会返回它。
答案 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,
};
}