C#如何检查对象是否属于某种类型 [英] c# how to check if an object is of a certain type

查看:475
本文介绍了C#如何检查对象是否属于某种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道检查对象的对象类型的过程是什么。

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.

更具体地说,我想检查GameScreen对象数组是否包含类型为GameplayScreen的GameScreen对象。

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


        }


推荐答案

您可以使用 运算符,例如:

You can check the type using is operator like:

if(screens[0] is GamePlayScreen)

或者如果您只需要 GamePlayScreen 可以使用数组中的对象:

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

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

请参阅: Enumerable.OfType 。它使用 System.Linq

这篇关于C#如何检查对象是否属于某种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆