检查,如果该对象是同一类型的 [英] Checking if the object is of same type

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

问题描述

您好,我需要知道如何检查,如果同一类型的C#中的对象



方案:

 类Base_Data {} 

类人:Base_Data {}
类电话:Base_data {}

类AnotherClass {

公共无效CheckObject(Base_Data数据){
如果(data.Equals(Person.GetType())){//< - Visual Studio 2010的给我错误,说我使用的人是一个类型,而不是变量。

}
}
}


解决方案

您可以使用 运营商:

 如果(数据是Person)
{
//数据是人
}

另一种可能是使用的 运营商:

 人员的人=数据的人; 
如果(人!= NULL)
{
//这里安全地使用人
}


Hello I need to know how to check if the object of the same type in C#.

Scenario:

class Base_Data{}

class Person : Base_Data {}
class Phone : Base_data {}

class AnotherClass{

   public void CheckObject(Base_Data data){
         if(data.Equals(Person.GetType())){ //<-- Visual Studio 2010 gives me error, says that I am using 'Person' is a type and not a variable.

       }
    }
}

解决方案

You could use the is operator:

if (data is Person)
{
    // data is an instance of Person
}

Another possibility is to use the as operator:

Person person = data as Person;
if (person != null)
{
    // safely use person here
}

这篇关于检查,如果该对象是同一类型的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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