Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

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

public void Getrecords(ref IList iList,T dataItem) 
{ 
  iList = Populate.GetList<dataItem>() // GetListis defined as GetList<T>
}

dataItem can be my order object or user object which will be decided at run time.The above does not work as it gives me this error The type 'T' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
public void GetRecords<T>(ref IList<T> iList, T dataitem)
{
}

What more are you looking for?

To Revised question:

 iList = Populate.GetList<dataItem>() 

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

 iList = Populate.GetList<T>() 

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<T> GetList<T>() 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<T>(ref IList<T> iList, T dataitem) where T: new() 
{
   iList = Populate.GetList<T>();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...