c# - 在 C# 中使用可选参数作为对象

标签 c# asp.net optional-parameters optional-arguments

我有这个代码:

public IHttpActionResult Get([FromUri]GetFilesRequest request)

如果请求为null,我想创建一个新的GetFilesRequest,因为在构造函数中我这样做是为了创建类的默认参数:

public GetFilesRequest()
    {
        Sort = "latest";
        Filter = "";
    }

所以我在想:

public IHttpActionResult Get([FromUri]GetFilesRequest request = new GetFilesRequest)

但是我收到这个警告:

'request' is of type 'GetFilesRequest'. A default parameter value of a reference type other than string can only be initialized with null.

最佳答案

否 - 默认值必须是编译时常量。您可以改用重载吗?

public IHttpActionResult Get()
{
     return Get(new GetFilesRequest());
}

关于c# - 在 C# 中使用可选参数作为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23770192/

相关文章:

asp.net - 如何使用 Javascript 在单击链接时重置 ASP.NET 下拉菜单?没有 JS 框架

python argparse 处理任意数字选项(如 HEAD(1))

c# - 从列表中删除相似的矩形

基于每个文件的 C# 编译器常量?

c# - 使用二维数组堆栈撤消不起作用

c# - Unity [UNET] 同步非玩家对象转换不工作

c# - 如何创建一个行为类似于 Session[] 集合的集合? C#

asp.net - 如何创建详细的错误页面?

ios - Swift:如何将函数类型值设置为可选变量?