创建泛型类的实例基于匿名类型 [英] Create Generic Class instance based on Anonymous Type

查看:192
本文介绍了创建泛型类的实例基于匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 ReportingComponent< T> ,其构造函数:

I have a class ReportingComponent<T>, which has the constructor:

public ReportingComponent(IQueryable<T> query) {}

我对LINQ的Northwind数据库查询,

I have Linq Query against the Northwind Database,

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

查询的类型是的IQueryable&LT;一个。&GT; ,其中一个'是一个匿名类型

Query is of type IQueryable<a'>, where a' is an anonymous type.

我想通过查询ReportingComponent创建一个新的实例。

I want to pass query to ReportingComponent to create a new instance.

什么是做到这一点的最好方法是什么?

What is the best way to do this?

亲切的问候。

推荐答案

写一个通用的方法和使用类型推断。我经常发现这个效果很好,如果你使用相同的名称作为通用其中创建一个静态的非泛型类:

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

然后在你的其他code,可致电:

Then in your other code you can call:

var report = ReportingComponent.CreateInstance(query);

编辑:我们需要一个非泛型类型的原因是,类型推断只发生于通用的方法的 - 即它引入了一个新的类型参数的方法。我们不能把,在泛型类型,因为我们还是必须要能够以调用该方法,这违背了整点指定的泛型类型:)

The reason we need a non-generic type is that type inference only occurs for generic methods - i.e. 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.

这篇关于创建泛型类的实例基于匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆