Question

The title is pretty confusing. I will try to explain with an example. Consider the code below:

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

I feel that I need to mention the type in above case for the ToList<T>() method. But how can I mention an anonymous type here?

Était-ce utile?

La solution

It is never possible to mention an anonymous type directly, but you should not need to. Generic type inference means that you don't need to specify the <T> in .ToList<T>() - the compiler will automatically inject the invented type.

There are only a few ways to refer to an anonymous type:

  • via someObj.GetType(), where someObj is an instance of an anonymous type
  • via generics, as a T, by calling a generic method via generic type inference (as in ToList())
  • various other usages of reflection, pulling in the T via GetGenericTypeParameters()

Autres conseils

This may be not what you are asking for, but if you later want to use the DataBoundItem for a row, you can do it this way:

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

with the support of this method:

public static class TypeExtensions
{
    public static T CastByPrototype<T>(object obj, T prototype)
    {
        return (T)obj;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top