2011-08-31 14 views
2

我想創建τ響應必須是非抽象類型與參數的構造函數,以便用它作爲參數τ響應

 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

任何幫助,將不勝感激..

回答

7

雖然您已經在ResponseBase<T>中定義了Tnew()約束,但編譯器要求您在其他使用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() 
+0

至於爲什麼會發生這種情況的原因是因爲你已經定義了''的'ResponseBase的'限制' T'的類型爲'new()',這意味着你以'T'形式傳入的任何對象都需要這個限制。 – fatty

+0

它的作品感謝您的快速回復 – Amit

+0

這工作,謝謝。我想更詳細地瞭解爲什麼編譯器需要'new()'約束? –

相關問題