简体   繁体   English

根据匿名类型创建通用类实例

[英]Create Generic Class instance based on Anonymous Type

I have a class ReportingComponent<T> , which has the constructor: 我有一个ReportingComponent<T>类,它具有构造函数:

public ReportingComponent(IQueryable<T> query) {}

I have Linq Query against the Northwind Database, 我有针对Northwind数据库的Linq查询,

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

Query is of type IQueryable<a'> , where a' is an anonymous type. 查询的类型为IQueryable<a'> ,其中a'是匿名类型。

I want to pass query to ReportingComponent to create a new instance. 我想将查询传递给ReportingComponent以创建一个新实例。

What is the best way to do this? 做这个的最好方式是什么?

Kind regards. 亲切的问候。

Write a generic method and use type inference. 编写通用方法并使用类型推断。 I often find this works well if you create a static nongeneric class with the same name as the generic one: 如果您创建一个与通用类同名的静态非通用类,我通常会发现这种方法很好用:

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

Then in your other code you can call: 然后,您可以在其他代码中调用:

var report = ReportingComponent.CreateInstance(query);

EDIT: The reason we need a non-generic type is that type inference only occurs for generic methods - ie a method which introduces a new type parameter. 编辑:我们需要非泛型类型的原因是类型推断仅对泛型方法进行 -即引入新类型参数的方法。 We can't put that in the generic type, as we'd still have to be able to specify the generic type in order to call the method, which defeats the whole point :) 我们不能将其放在泛型类型中,因为我们仍然必须能够指定泛型类型才能调用该方法,这使整个观点失去了:)

I have a blog post which goes into more details. 我有一篇博客文章 ,其中有更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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