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

时间:2011-08-31 07:14:45

标签: 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;
    }

和类已被定义为

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

    [DataMember]
    public Result<T> Result { get; set; }
}

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

任何帮助将不胜感激..

1 个答案:

答案 0 :(得分:8)

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

您只需在方法中将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()