C# A problem with casting
I have that code:
myDat开发者_StackOverflow社区aGrid
is an object passed to the method. I know it is type of OvserveableCollection
of different types.
All I need is to cast that object to OvserveableCollection<T>
(it implements the IEnumerable
interface)
//get element's type
Type entryType = (myDataGrid as IEnumerable).AsQueryable().ElementType;
foreach (var item in (IEnumerable<entryType>)myDataGrid)
{}
but the compiler doesn't know the entryType
in the loop header. Why ?
You can't use a runtime Type
instance as a generic type parameter unless you use reflection (MakeGenericMethod()
/ MakeGenericType()
). However I doubt it would help anyway! In this scenario, either use the non-generic IEnumerable
(no <T>
) API, or perhaps cast to a known interface/subclass, or use dynamic
as a last resort duck-typing.
You can also use MakeGenericMethod()
etc, but that is more involved and almost certainly slower.
For example:
foreach(object item in (IEnumerable)myDataGrid)
{
// tada!
}
Another trick can be to use dynamic
to invoke the generic code:
public void Iterate<T>(IEnumerable<T> data)
{
foreach(T item in data) {...}
}
...
dynamic evil = myDataGrid;
Iterate(evil);
You're trying to use a Type
variable as a type argument for a generic type. Generics don't work that way - you have to use a compile-time type as the type argument. (That compile-time type can be a type parameter itself, if you're doing this in a generic method.)
It's hard to know how to advise you to change the code without knowing more about your requirements though - what do you need to do with the items?
You can't cast to a "runtime type"... in order to "write" the instructions which actually implement that cast, the compiler requires the Type... which really just means that the Type must be known at COMPILE time.
The ONLY way I've ever found around this limitation was code-generator (of one sort or another) to "manually" generate the IL instructions to perform the cast. It's hard to know what to recommend unless we know a lot about your actual requirements (and constraints).
Cheers. Keith.
精彩评论