2013-04-22 39 views
4

我試圖實現一個方法,它接受一個泛型T並返回一個T 。錯誤:'T'必須是具有公共無參數構造函數的非抽象類型,才能將其用作參數'T'

public static List<T> GetMessages<T>(string query, int count, SqlConnection sqlconnection) 
     where T : ITable, new() 
    { 
     List<T> messages = new List<T>(); 
     List<T> errorMessages = new List<T>(); 

     DataSet response = DBUtils.ExecuteQueryScriptWithConnection(query, sqlconnection); 

     for (int i = 0; i < response.Tables[0].Rows.Count; ++i) 
     { 
      T message = new T(); 

      DataRow row = response.Tables[0].Rows[i]; 
      message.Id = Convert.ToInt32(row[0]); 
      message.CreatedDate = Convert.ToDateTime(row[1]);     
     } 

     return messages; 
    } 

但是,當我把它從另一種方法,我得到的錯誤:

 List<T> messages = TableHelpers.GetMessages<T>(query, 1000, sqlconnection); 
:我是從調用這個

'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method ' CIHelpers.TableHelpers.GetMessages<T>(string, int, System.Data.SqlClient.SqlConnection) '

代碼210

實現ITable的類(我傳遞的類型T在這裏。

public class MessageReceived : ITable 
{ 
    public int Id { get; set; } 
    public DateTime CreatedDate { get; set; } 

    string query = String.Format(@"select Id, CreatedDate, from MessageReceived where createddate > '2013-04-18 00:00:00.0000000'"); 

    public MessageReceived() 
    { 

    } 
} 

我做錯了什麼?

回答

5

調用代碼中的T需要具有相同的約束條件。

否則,有人可以用沒有構造函數的T調用你的包裝函數。

+0

謝謝,工作! :) – raleign 2013-04-22 20:39:28

+0

@raleign在這種情況下,你應該考慮[接受](http://meta.stackexchange.com/a/5235/130186)這個答案。 – svick 2013-04-22 20:41:21

+4

@svick,正如你的鏈接所解釋的那樣,提問者仍然需要等待6分鐘才能接受答案。請考慮給他一些鬆懈。 – 2013-04-22 20:46:20

相關問題