c# how to check if an object is of a certain type

久未见 提交于 2019-12-11 23:37:43

问题


I am just wondering what the process is for checking the object type of something.

Basically I have an array of parent objects and I want to check if one of those objects is of a particular child type.

more specifically, I want to check if an array of GameScreen objects contains a GameScreen object of type GameplayScreen.

        GameScreen[] screens = mScreenManager.GetScreens();

        // loop through array and check if the object equals gameplayscreen


        }

回答1:


You can check the type using is operator like:

if(screens[0] is GamePlayScreen)

Or if you just need GamePlayScreen type objects from your array you can use :

GamePlayScreen[] items = screens.OfType<GamePlayScreen>().ToArray();

See: Enumerable.OfType. It uses System.Linq




回答2:


Use the is keyword when you want to check a type.

class Foo {}
class SuperFoo : Foo {}

bool IsSuperFoo(Foo foo)
{
    if (Foo is SuperFoo) return true;
    return false;
}

You can do the same for your GamePlayScreen.



来源:https://stackoverflow.com/questions/23087511/c-sharp-how-to-check-if-an-object-is-of-a-certain-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!