Why can't I instantiate a generic class inferring types from anonymous objects?

倖福魔咒の 提交于 2019-12-06 07:53:44

You can't put together generics, anonymous types and type inference in constructors. The compiler just won't get it. You can create a workaround through a helper class such as:

public static class InvalidResponseExceptionHelper
{
    public static InvalidResponseException<TReq, TResp> Create<TReq, TResp>
        (string message, TReq requestData, TResp responseData)
    {
        return new InvalidResponseException<TReq, TResp>(message, 
            requestData, responseData);
    }
}

Also, I didn't mention it, but your InvalidResponseException class won't compile unless heavily modified. The concept of your question went through, however.

Your example is incorrect. You donot need to specify generic types to constructors. They are already known.

The following line is invalid, and wont compile

public InvalidResponseException<TReq, TResp>(string message) // TReq,TResp are already known to constructor

I think you need something similar to below

public  class InvalidResponseException<TReq, TResp> : Exception
{
    public TReq RequestData { get; protected set; }
    public TResp ResponseData { get; protected set; }

    public InvalidResponseException (string message):
        this(message, default(TReq), default(TResp))    
    {
    }
    public InvalidResponseException (string message, TReq requestData, TResp responseData)  : base(message)
    {
        RequestData = requestData;
        ResponseData = responseData;
    }

}

Then you try below (to make use of type inference)

  throw new InvalidResponseException(exceptionMessage, "Exception Request", "Exception Response");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!