代码之家  ›  专栏  ›  技术社区  ›  SharePoint Newbie

基于匿名类型创建泛型类实例

  •  12
  • SharePoint Newbie  · 技术社区  · 16 年前

    我有一节课 ReportingComponent<T> ,其具有构造函数:

    public ReportingComponent(IQueryable<T> query) {}
    

    我有关于Northwind数据库的Linq查询,

    var query = context.Order_Details.Select(a => new 
    { 
        a.OrderID, 
        a.Product.ProductName,
        a.Order.OrderDate
    });
    

    查询的类型为 IQueryable<a'> ,其中“是匿名类型。

    我想将查询传递给reportingcomponent以创建新实例。

    最好的方法是什么?

    亲切的问候。

    1 回复  |  直到 10 年前
        1
  •  17
  •   CodeCaster    10 年前

    编写一个通用方法并使用类型推断。如果您创建一个与通用类同名的静态非能量类,我通常会发现这一点很好:

    public static class ReportingComponent
    {
      public static ReportingComponent<T> CreateInstance<T> (IQueryable<T> query)
      {
        return new ReportingComponent<T>(query);
      }
    }
    

    然后在您的其他代码中,您可以调用:

    var report = ReportingComponent.CreateInstance(query);
    

    编辑:我们需要非泛型类型的原因是类型推断只发生在泛型 方法 -即引入新类型参数的方法。我们不能将其放入泛型类型中,因为我们仍然必须能够指定泛型类型才能调用方法,这会破坏整个点:)

    我有一个 blog post 更详细。