我正在尝试创建一个像
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
任何帮助,将不胜感激..
最佳答案
尽管您已经在new()
中为T
定义了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()