C#强制包含可选参数?

时间:2019-01-21 22:30:41

标签: c# asp.net-core

我从Microsoft获得以下方法:

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; }
}

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

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

简单的答案是,不是在没有导致错误的可选参数的情况下调用方法,而是在调用方法。如果您要在lambda中调用该方法,则只有在指定了可选参数后,该方法才能起作用。