How to check the type of cycle?

I know how to directly check the type of a field. But how could I implement something like this

private bool checkJumpObstacle(Type type) { foreach (GameObject3D go in GameItems) { if (go is type) // won't accept 'type' { return true; } } return false; } 

For the type, I would like to pass Car , House or Human as a parameter (these are all classes). But such code does not work.

+4
source share
1 answer

EDIT: It is actually even easier to use Type.IsInstanceOfType if you cannot make it a general method:

 private bool CheckJumpObstacle(Type type) { return GameItems.Any(x =>type.IsInstanceOfType(x)); } 

It looks like you probably want Type.IsAssignableFrom

 if (go != null && type.IsAssignableFrom(go.GetType()); 

Note that this assumes that you want the inherited types to match.

Also, if at all possible, use generics instead. Among other things, this will make the method very simple:

 private bool CheckJumpObstacle<T>() { return GameItems.OfType<T>().Any(); } 

Even without this, you can still use LINQ to simplify it:

 private bool CheckJumpObstacle(Type type) { return GameItems.Any(x => x != null && type.IsAssignableFrom(x.GetType())); } 

Obviously, if you do not expect any null values, you can get rid of invalidation checking.

+16
source

All Articles