如何在使用泛型类型时指定匿名类型的类型

本文关键字:类型 泛型类型 | 更新日期: 2023-09-27 17:50:44

标题很混乱。我将试着用一个例子来解释。考虑下面的代码:

String[] str={"Apple","Banana","Cherry","Orange"};
var anoCollection=from e in str select new
                                         {
                                          ch=e[0],
                                          length=e.Length
                                         }
dataGridView.DataSource=anoCollection.ToList(); //TypeInitializationException

我觉得我需要在上面的例子中提到ToList<T>()方法的类型。但我怎么能在这里提到匿名类型呢?

如何在使用泛型类型时指定匿名类型的类型

直接提到匿名类型是不可能的,但您不应该需要这样做。泛型类型推断意味着你不需要在.ToList<T>()中指定<T>——编译器会自动注入发明的类型。

只有几种方法可以引用匿名类型:

  • 通过someObj.GetType(),其中someObj是匿名类型的实例
  • 通过泛型,作为T,通过泛型类型推断调用泛型方法(如ToList())
  • 反射的各种其他用法,通过GetGenericTypeParameters()拉入T

这可能不是您想要的,但是如果您以后想要为一行使用DataBoundItem,您可以这样做:

var item = TypeExtensions.CastByPrototype(row.DataBoundItem, new { ch = 'a', length = 0});
//you can use item.ch and item.length here
Trace.WriteLine(item.ch);

在这个方法的支持下:

public static class TypeExtensions
{
    public static T CastByPrototype<T>(object obj, T prototype)
    {
        return (T)obj;
    }
}