【问题标题】:TResponse must be a non abstract type with a parameterless constructor in order to use it as parameter TResponseTResponse 必须是具有无参数构造函数的非抽象类型才能将其用作参数 TResponse
【发布时间】:2011-08-31 07:14:45
【问题描述】:

我正在尝试创建一个类似

的函数
        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

任何帮助将不胜感激..

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    尽管您在ResponseBase&lt;T&gt; 中为T 定义了new() 约束,但编译器要求您在一般使用ResponseBase&lt;T&gt; 的其他类中声明相同的约束。

    您所要做的就是在您的方法中将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()
    

    【讨论】:

    • 至于发生这种情况的原因是因为您为 ResponseBase&lt;T&gt; 定义了 &lt;T&gt; 以将 T 限制为 new() 类型,这意味着您传入的任何对象为T 需要有这个限制。
    • 这行得通,谢谢。我想更详细地了解,为什么编译器需要new() 约束?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多