【问题标题】:Call a generic method with a generic method用泛型方法调用泛型方法
【发布时间】:2011-05-18 10:13:00
【问题描述】:

我很生气,因为我想从另一个泛型方法中调用一个泛型方法..

这是我的代码:

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;  
}

所以实际上当我调用 ToList 时,谁是 DataTable 类的扩展(学习了Here

编译器说 Y 不是非抽象类型,他不能将它用于 .ToList 泛型方法..

我做错了什么?

感谢阅读。。

【问题讨论】:

  • 也许从可编译代码开始?我认为应该是dt.AsEnumerable().ToList&lt;T&gt;()
  • @Henk Holterman:OP 似乎使用的是自定义扩展方法,而不是 LINQ to Objects Enumerable.ToList 方法。
  • @Ani:我想是的,但那是值得一提的。
  • @Henk Holterman “..我打电话给 ToList 谁是 DataTable 类的扩展(在这里学习)”这是提..

标签: c# generics


【解决方案1】:

将方法签名更改为:

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

您需要这样做的原因是因为您使用的自定义扩展方法在其泛型类型参数上施加了new() 约束。它当然需要,因为它创建了这种类型的 instances 来填充返回的列表。

显然,您还必须使用表示具有公共无参数构造函数的非抽象类型的泛型类型参数调用此方法。

【讨论】:

    【解决方案2】:

    听起来你需要:

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

    【讨论】:

    • WHERE Y : new() 和 where Y: class, new() 有什么区别?感谢您的回复!
    • @bAN - where Y : class 确保Y 是一个引用类型(很可能是class)。实际上你可能不需要这个 - 重新阅读链接的ToList 它只需要where Y : new(),所以@Ani 的答案是正确的。
    【解决方案3】:

    看起来 ToList 函数对类型有限制:

    where T : new()
    

    我认为,如果您对函数使用相同的约束(但使用 Y 而不是 T),它应该可以工作。

    您可以在此处阅读更多信息:http://msdn.microsoft.com/en-us/library/sd2w2ew5(v=VS.80).aspx

    【讨论】:

      【解决方案4】:

      我猜你需要使用 where 子句来限制你的泛型类型。

      【讨论】:

        猜你喜欢
        • 2011-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多