实例化匿名类型将返回null

Dan*_*son 0 c# anonymous-types

我在代码中实例化匿名类型时遇到问题.

出于某种原因,TResponse response = default(TResponse);返回null,即使TResponse有一个构造函数.

我傻了吗?!

类:

public class MyClass
{
  public MyResponse GetResponse(MyRequest request)
  {
    return Service<MyRequest, MyResponse>.MakeRequest(
      request,
      delegate() {
        return AnotherService.GetRequest(request);
      }
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

服务类

public static class Service<TRequest, TResponse>
  where TRequest : IRequest
  where TResponse : IResponse
{
  public delegate TResponse UseDelegate();

  public TResponse MakeRequest(TRequest request, UseDelegate codeBlock)
  {
    TResponse response = default(TResponse); // <-- Returns nulll

    response = codeBlock();

    return response;
  }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

正如Brandon所说,default返回null任何参考类型.

但是,我不明白你为什么要使用它 - 你分配的值将会被返回值覆盖codeBlock().换句话说,您可以将MakeRequest方法更改为:

public TResponse MakeRequest(TRequest request, UseDelegate codeBlock)
{
    TResponse response = codeBlock();
    return response;
}
Run Code Online (Sandbox Code Playgroud)

甚至:

public TResponse MakeRequest(TRequest request, UseDelegate codeBlock)
{
    return codeBlock();
}
Run Code Online (Sandbox Code Playgroud)

我假设现实中有更多的代码......但如果你真的想调用无参数构造函数,你可以用以下方法约束TResponse:

where TResponse : IResponse, new()
Run Code Online (Sandbox Code Playgroud)

然后使用:

TResponse response = new TResponse();
Run Code Online (Sandbox Code Playgroud)

这样你就可以得到一个TResponse具有无参数构造函数的编译时保证; 只是在Activator.CreateInstance(typeof(TResponse))没有约束的情况下使用TResponse会工作,但是会延迟发现你试图使用没有无参数构造函数的响应类型的问题.

此外,我没有在您的代码中看到任何匿名类型 - 匿名类型具有无参数构造函数的唯一方法是使用:

new {}
Run Code Online (Sandbox Code Playgroud)

这有点无意义.