TResponse必须是非抽象类型,带有无参数构造函数,以便将其用作参数TResponse

Ami*_*mit 2 c# generics

我正在尝试创建一个类似的函数

        public static TResponse Run<TService, TResponse>(Controller mvcController,            IServiceController serviceController, Func<TService, TResponse> action, bool suppressErrors)
        where TService : ICommunicationObject
        where TResponse : ResponseBase<TResponse>
    {
        TResponse response = serviceController.Run<TService, TResponse>(action);
        if (!suppressErrors)
            response.Result.Errors.ToList().ForEach(i => mvcController.ModelState.AddModelError(UniqueKey.ValidationMessage, i.Message));
        return response;
    }
Run Code Online (Sandbox Code Playgroud)

和类被定义为

[DataContract]
public class ResponseBase<T> where T: new()
{
    public ResponseBase()
    {
        Result = new Result<T>();
    }

    [DataMember]
    public Result<T> Result { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我收到编译错误,因为TResponse必须是非抽象类型,带有无参数构造函数才能将其用作参数TResponse

任何帮助,将不胜感激..

Bol*_*ock 8

虽然您已new()Tin 定义了约束ResponseBase<T>,但编译器要求您在ResponseBase<T>通用的其他类中声明相同的约束.

您所要做的就是在方法中添加new()约束TResponse:

public static TResponse Run<TService, TResponse>(Controller mvcController, IServiceController serviceController, Func<TService, TResponse> action, bool suppressErrors)
    where TService : ICommunicationObject
    where TResponse : ResponseBase<TResponse>, new()
Run Code Online (Sandbox Code Playgroud)