Aag*_*nor 0 c# casting primitive-types
in my C# program, I need to cast an object to a IEnumerable<object>. All I know about that object is, that it is a list (Type.IsGenericType):
IEnumerable<object> iEnu = myObject as IEnumerable<object>;
if (iEnu != null)
foreach (object o in iEnu)
// do stuff
Run Code Online (Sandbox Code Playgroud)
As long as the type of the list is not a primitiv, it works fine, as all classes inherit from object. But primitives doesn't. Therefore, the cast to IEnumerable<object> returns null. I'd need to cast to IEnumerable<int>, if it's a list of integer, to IEnumerable<bool> if it's a list of booleans and so on. Naturally, i want just one generic cast.
Any idea, what to do to get the primitive lists as well?
只需使用IEnumerable代替IEnumerable<object>; 虽然int[]没有实现IEnumerable<object>,但它确实实现了IEnumerable:
IEnumerable enumerable = myObject as IEnumerable;
if (enumerable != null)
{
foreach (object o in enumerable)
{
// do stuff
}
}
Run Code Online (Sandbox Code Playgroud)