开发者

Call a generic method with a generic method

I am annoyed because I would开发者_如何学编程 like to call a generic method from a another generic method..

Here is my code:

public List<Y> GetList<Y>(
                string aTableName,
                bool aWithNoChoice)
{
  this.TableName = aTableName;
  this.WithNoChoice = aWithNoChoice;

  DataTable dt = ReturnResults.ReturnDataTable("spp_GetSpecificParametersList", this);

  //extension de la classe datatable
  List<Y> resultList = (List<Y>)dt.ToList<Y>();

  return resultList;  
}

So in fact when I call ToList who is an extension to DataTable class (learned Here)

The compiler says that Y is not a non-abstract Type and he can't use it for .ToList<> generic method..

What am I doing wrong?

Thanks for reading..


Change the method signature to:

public List<Y> GetList<Y>(
                string aTableName,
                bool aWithNoChoice) where Y: new()

The reason you need that is because the custom extension-method you use imposes the new() constraint on its generic type argument. It certainly needs to, since it creates instances of this type to populate the returned list.

Obviously, you will also have to call this method with a generic type argument that represents a non-abstract type that has a public parameterless constructor.


It sounds like you need:

public List<Y> GetList<Y>(
     string aTableName,
     bool aWithNoChoice) where Y : class, new()
{ ... }


It looks like the ToList function has a constraint on the type:

where T : new()

I think that if you use that same constraint on your function (but with Y instead of T) it should work.

You can read more about it here: http://msdn.microsoft.com/en-us/library/sd2w2ew5(v=VS.80).aspx


I guess you need to constraints on your generic type by using where clause.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜