【问题标题】:C# forcing to include optional parameters?C# 强制包含可选参数?
【发布时间】:2019-06-15 08:32:08
【问题描述】:

我有以下来自微软的方法:

public static string GetPathByAction(this LinkGenerator generator, 
   HttpContext httpContext, 
   string action = null, 
   string controller = null, 
   object values = null, 
   PathString? pathBase = null, 
   FragmentString fragment = default(FragmentString), 
   LinkOptions options = null);

当我在没有最后一个参数的情况下调用此方法时,我得到了错误:

  An expression tree may not contain a call or invocation that uses optional arguments

如果参数是选项,为什么会出现这样的错误?

LinkGenerator 是这个类:
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.routing.linkgenerator?view=aspnetcore-2.2

更新

我在一个类中注入 LinkGenerator,如下所示(这段代码没有出错,因为我传递了所有参数):

public class RequestHandler : IRequestHandler<Request, Response>> {

  private LinkGenerator _linkGenerator;

  public RequestHandler(LinkGenerator linkGenerator) {

    _linkGenerator = linkGenerator;

  } 

  public async Task<Response> Handle(Request request, CancellationToken cancellationToken) {

    List<File> files = getFiles();    

    // WORKS
    var url = _linkGenerator.GetUriByAction(action: "GetByUserId", controller: "FileController", null, "", new HostString());

    // DOES NOT WORK
    var = await files
      .Select(x => new Response {
        Id = x.File.Id,
        Url = _linkGenerator.GetUriByAction(action: "GetByUserId", controller: "FileController", null, "", new HostString())
      }).ToListAsync();

    // Remaining code 

  }

}

public class File { 
  public Int32 Id { get; set; }
  public String Url { get; set; }
}

【问题讨论】:

标签: c# asp.net-core


【解决方案1】:
【解决方案2】:

另请参阅:An expression tree may not contain a call or invocation that uses optional arguments

简单的答案不是调用没有导致错误的可选参数的方法,而是调用的方式。如果您在 lambda 中调用该方法,则它仅在您指定可选参数时才有效。

【讨论】:

  • 我读过那篇文章,但我不清楚......所以我需要传递所有参数,即使它们是可选的?这毫无意义……即使在 Microsoft 文档中,它们也被标记为可选。有什么办法吗?
  • 您可以在表达式树之外调用该函数,或者您可以创建一个调用该函数的包装器并改用它。
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-13
相关资源
最近更新 更多