简体   繁体   中英

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

我想你需要使用where子句约束你的泛型类型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM