Why does this generic method require T to have a public, parameterless constructor?

前端 未结 5 777
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 01:09
public void Getrecords(ref IList iList,T dataItem) 
{ 
  iList = Populate.GetList() // GetListis defined as GetList
}

data

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 01:46

    public void GetRecords(ref IList iList, T dataitem)
    {
    }
    

    What more are you looking for?

    To Revised question:

     iList = Populate.GetList() 
    

    "dataitem" is a variable. You want to specify a type there:

     iList = Populate.GetList() 
    

    The type 'T' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type GetList:new()

    This is saying that when you defined Populate.GetList(), you declared it like this:

    IList GetList() where T: new() 
    {...}
    

    That tells the compiler that GetList can only use types that have a public parameterless constructor. You use T to create a GetList method in GetRecords (T refers to different types here), you have to put the same limitation on it:

    public void GetRecords(ref IList iList, T dataitem) where T: new() 
    {
       iList = Populate.GetList();
    }
    

提交回复
热议问题